Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat:register vesting type, add support for delegation/undelegation of native token #127

Merged

Conversation

leonz789
Copy link
Contributor

@leonz789 leonz789 commented Jul 10, 2024

Description

tasks

  • tests
  • cli

This PR add support for native token's delegation/undelegation, the assets info of native token will be taken care by bank/auth module, and delgation, operator info would still be maintained by assets module and delegation module. As for the staker info query from assets module we calculation the results using data from bank module.

Changes

Notable changes:

  • register vesting account type
  • add support for native token delegation/undelegation
  • register dogfood's hooks in delegation
  • update tests in delegation module corresponding to dogfood hooks
  • avoid doing UpdateStakerAssetState when it is exo-native-token related
  • update msg proto define to
    • identify assetID
    • replace map with list

Closes #XXX

Summary by CodeRabbit

  • New Features

    • Introduced commands for delegating and undelegating native tokens via the CLI, enhancing user control over native token management.
  • Improvements

    • Enhanced retrieval of staker-specific asset information, including native assets, for more accurate and detailed asset management.
    • Added new interfaces for BankKeeper and delegation management to improve asset management and account operations.
  • Constants

    • Added new constants for native assets, including identifiers and denominations, to streamline asset referencing.
  • Refactor

    • Updated delegation-related structures and message definitions for improved clarity and functionality.
    • Enhanced the Keeper struct to manage accounts and banking operations more effectively.

Copy link
Contributor

coderabbitai bot commented Jul 10, 2024

Walkthrough

The recent updates introduce significant enhancements to the Exocore Network's codebase, focusing on the integration of the vesting module and improvements to asset management and delegation functionalities. Key changes include the addition of new constants for native assets, the introduction of CLI commands for delegating and undelegating tokens, and the restructuring of delegation-related messages. These modifications streamline asset interactions for stakers and enhance the overall delegation process.

Changes

Files/Paths Change Summary
app/app.go Integrated the vesting module, updating module initialization and keeper dependencies.
proto/exocore/delegation/v1/tx.proto Removed DelegationApproveInfo, modified per_operator_amounts, and added asset_id to messages.
x/assets/client/cli/tx.go Removed validation step in UpdateParams, affecting transaction processing.
x/assets/keeper/staker_asset.go Enhanced GetStakerSpecifiedAssetInfo for native assets, including balance and delegation info.
x/assets/types/general.go Added constants for native assets and modified existing constants to improve flexibility.
x/assets/keeper/expected_keepers.go Introduced delegationKeeper interface for consistent delegation data access.
x/assets/keeper/keeper.go Added bk and dk fields to Keeper struct and updated constructor.
x/assets/keeper/staker_asset_test.go Updated test to reflect new staker ID format.
x/delegation/client/cli/tx_delegation_native.go Introduced CLI commands CmdDelegate() and CmdUndelegate() for managing native token delegation.
x/delegation/types/msg.go Added functions NewMsgDelegation and NewMsgUndelegation for message instantiation.
x/delegation/keeper/msg_server.go Implemented logic for DelegateAssetToOperator and UndelegateAssetFromOperator functions.
x/delegation/types/expected_keepers.go Added BankKeeper and AccountKeeper interfaces for enhanced account and asset management.
x/delegation/types/errors.go Introduced new error variable ErrInvalidAssetID for handling invalid asset IDs.
x/delegation/types/general.go Added constants for pool names related to delegation.

Possibly related PRs

Suggested reviewers

  • cloud8little
  • MaxMustermann2
  • trestinlsd
  • bwhour
  • mikebraver
  • TimmyExogenous

Poem

In the meadow where code takes flight,
New features shimmer, a joyful sight.
Native assets join the dance,
Stakers leap in a lively prance.
With each change, we grow and thrive,
A vibrant network, alive, alive!
🐇🌼✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    -- I pushed a fix in commit <commit_id>, please review it.
    -- Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    -- @coderabbitai generate unit testing code for this file.
    -- @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    -- @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    -- @coderabbitai read src/utils.ts and generate unit testing code.
    -- @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    -- @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai or @coderabbitai title anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

parsedStakerID := strings.Split(record.StakerID, "-")
stakerAddr := sdk.AccAddress(hexutil.MustDecode(parsedStakerID[0]))
if err := k.bankKeeper.UndelegateCoinsFromModuleToAccount(ctx, types.DelegatedPoolName, stakerAddr, sdk.NewCoins(sdk.NewCoin(assetstypes.NativeAssetDenom, record.ActualCompletedAmount))); err != nil {
panic(err)

Check warning

Code scanning / CodeQL

Panic in BeginBock or EndBlock consensus methods Warning

Possible panics in BeginBock- or EndBlock-related consensus methods could cause a chain halt
WaitUnbondingAmount: recordAmountNeg,
})
if err != nil {
panic(err)

Check warning

Code scanning / CodeQL

Panic in BeginBock or EndBlock consensus methods Warning

Possible panics in BeginBock- or EndBlock-related consensus methods could cause a chain halt
parsedStakerID := strings.Split(record.StakerID, "-")
stakerAddr := sdk.AccAddress(hexutil.MustDecode(parsedStakerID[0]))
if err := k.bankKeeper.UndelegateCoinsFromModuleToAccount(ctx, types.DelegatedPoolName, stakerAddr, sdk.NewCoins(sdk.NewCoin(assetstypes.NativeAssetDenom, record.ActualCompletedAmount))); err != nil {
panic(err)

Check warning

Code scanning / CodeQL

Panic in BeginBock or EndBlock consensus methods Warning

path flow from Begin/EndBlock to a panic call
WaitUnbondingAmount: recordAmountNeg,
})
if err != nil {
panic(err)

Check warning

Code scanning / CodeQL

Panic in BeginBock or EndBlock consensus methods Warning

path flow from Begin/EndBlock to a panic call
@leonz789 leonz789 changed the title feat:register vesting type, add support for delegation/undelegation of native token [WIP] feat:register vesting type, add support for delegation/undelegation of native token Jul 10, 2024
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Outside diff range and nitpick comments (1)
x/delegation/keeper/abci.go (1)

Line range hint 41-85:
Replace panic with proper error handling.

Using panic in the EndBlock function can cause the chain to halt. Replace panic with proper error handling to ensure the stability of the application.

- if err != nil {
-     panic(err)
- }
+ if err != nil {
+     k.Logger(ctx).Error("Failed to update staker asset state", "error", err)
+     continue
+ }

- if err != nil {
-     panic(err)
- }
+ if err != nil {
+     k.Logger(ctx).Error("Failed to update operator asset state", "error", err)
+     continue
+ }

- if err != nil {
-     panic(err)
- }
+ if err != nil {
+     k.Logger(ctx).Error("Failed to delete undelegation record", "error", err)
+     continue
+ }
Tools
GitHub Check: CodeQL

[warning] 76-76: Panic in BeginBock or EndBlock consensus methods
Possible panics in BeginBock- or EndBlock-related consensus methods could cause a chain halt


[warning] 84-84: Panic in BeginBock or EndBlock consensus methods
Possible panics in BeginBock- or EndBlock-related consensus methods could cause a chain halt


[warning] 76-76: Panic in BeginBock or EndBlock consensus methods
path flow from Begin/EndBlock to a panic call


[warning] 84-84: Panic in BeginBock or EndBlock consensus methods
path flow from Begin/EndBlock to a panic call

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 7cd1cfd and 902c0ae.

Files selected for processing (10)
  • app/app.go (8 hunks)
  • x/assets/types/general.go (1 hunks)
  • x/delegation/keeper/abci.go (4 hunks)
  • x/delegation/keeper/cross_chain_tx_process.go (1 hunks)
  • x/delegation/keeper/delegation_state.go (1 hunks)
  • x/delegation/keeper/keeper.go (1 hunks)
  • x/delegation/keeper/un_delegation_state.go (1 hunks)
  • x/delegation/types/cross_chain_params.go (1 hunks)
  • x/delegation/types/expected_keepers.go (1 hunks)
  • x/delegation/types/general.go (1 hunks)
Files skipped from review due to trivial changes (3)
  • x/delegation/keeper/keeper.go
  • x/delegation/keeper/un_delegation_state.go
  • x/delegation/types/general.go
Additional context used
GitHub Check: CodeQL
x/delegation/keeper/abci.go

[warning] 76-76: Panic in BeginBock or EndBlock consensus methods
Possible panics in BeginBock- or EndBlock-related consensus methods could cause a chain halt


[warning] 84-84: Panic in BeginBock or EndBlock consensus methods
Possible panics in BeginBock- or EndBlock-related consensus methods could cause a chain halt


[warning] 76-76: Panic in BeginBock or EndBlock consensus methods
path flow from Begin/EndBlock to a panic call


[warning] 84-84: Panic in BeginBock or EndBlock consensus methods
path flow from Begin/EndBlock to a panic call

Additional comments not posted (8)
x/delegation/types/cross_chain_params.go (1)

22-42: LGTM! But verify the function usage in the codebase.

The code changes are approved.

However, ensure that all function calls to NewDelegationOrUndelegationParams match the new signature.

x/delegation/types/expected_keepers.go (1)

55-59: LGTM! But verify the interface implementation.

The code changes are approved.

However, ensure that all implementations of the BankKeeper interface include the new methods.

x/assets/types/general.go (1)

14-21: LGTM!

The addition of constants for native assets improves code readability and maintainability.

x/delegation/keeper/cross_chain_tx_process.go (1)

41-64: Ensure Correctness of Native Asset Handling.

The new logic for handling native assets looks correct, but verify the following:

  1. Ensure assetstype.NativeAssetID and assetstype.NativeAssetDenom are correctly defined.
  2. Confirm DelegateCoinsFromAccountToModule correctly handles the transfer of native assets.
  3. Ensure all necessary tests are updated or added for this new logic.
x/delegation/keeper/delegation_state.go (1)

149-149: Verify Consistency of Updated Error Handling.

The updated error handling method using delegationtype.ErrNoKeyInTheStore.Wrapf looks correct. Ensure this method is consistently used across the codebase for error wrapping.

app/app.go (3)

123-124: Verify Necessity and Correctness of New Imports.

The imports for vesting and vestingtypes are added. Ensure these are necessary for the new functionalities and correctly imported.


259-259: Ensure Correct Integration of vesting.AppModuleBasic{}.

The addition of vesting.AppModuleBasic{} to the module list looks correct. Verify that this integration is necessary and correctly implemented.


292-293: Verify Integration of vestingtypes.ModuleName.

The integration of vestingtypes.ModuleName in the NewExocoreApp function looks correct. Ensure this integration is necessary and correctly implemented.

@github-actions github-actions bot added the C:CLI label Jul 15, 2024
@leonz789 leonz789 changed the title [WIP] feat:register vesting type, add support for delegation/undelegation of native token feat:register vesting type, add support for delegation/undelegation of native token Jul 15, 2024
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 902c0ae and dc1d9ef.

Files selected for processing (16)
  • app/app.go (11 hunks)
  • testutil/utils.go (1 hunks)
  • x/assets/keeper/expected_keepers.go (1 hunks)
  • x/assets/keeper/keeper.go (1 hunks)
  • x/assets/keeper/staker_asset.go (2 hunks)
  • x/assets/types/expected_keepers.go (1 hunks)
  • x/assets/types/general.go (1 hunks)
  • x/delegation/client/cli/tx.go (1 hunks)
  • x/delegation/client/cli/tx_delegation_native.go (1 hunks)
  • x/delegation/keeper/abci.go (4 hunks)
  • x/delegation/keeper/delegation_op_test.go (7 hunks)
  • x/delegation/keeper/keeper.go (2 hunks)
  • x/delegation/keeper/msg_server.go (1 hunks)
  • x/delegation/keeper/setup_test.go (2 hunks)
  • x/delegation/types/expected_keepers.go (1 hunks)
  • x/delegation/types/msg.go (2 hunks)
Files skipped from review due to trivial changes (3)
  • testutil/utils.go
  • x/assets/keeper/expected_keepers.go
  • x/assets/types/expected_keepers.go
Files skipped from review as they are similar to previous changes (5)
  • app/app.go
  • x/assets/types/general.go
  • x/delegation/keeper/abci.go
  • x/delegation/keeper/keeper.go
  • x/delegation/types/expected_keepers.go
Additional comments not posted (5)
x/delegation/keeper/setup_test.go (1)

23-23: Verify the usage of the new field accAddr.

Ensure that the newly added field accAddr is properly utilized in the test suite. It's important to check if it's being set and used correctly in the tests to prevent any issues during runtime.

Verification successful

The field accAddr is properly utilized in the test suite.

The field accAddr is set and used in the x/delegation/keeper/delegation_op_test.go file, confirming its integration into the test cases.

  • x/delegation/keeper/delegation_op_test.go: Proper setting and usage of accAddr.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of the new field `accAddr` in the test suite.

# Test: Search for the field usage. Expect: Proper setting and usage in the test methods.
rg --type go -A 5 $'accAddr' x/delegation/keeper/setup_test.go

Length of output: 166


Script:

#!/bin/bash
# Description: Search for all occurrences of the field `accAddr` in the test suite file to verify its usage.

# Test: Search for the field usage. Expect: Proper setting and usage in the test methods.
rg 'accAddr' x/delegation/keeper/setup_test.go

Length of output: 79


Script:

#!/bin/bash
# Description: Search for all occurrences of the field `accAddr` in the `x/delegation/keeper` directory to verify its usage.

# Test: Search for the field usage. Expect: Proper setting and usage in the test methods.
rg 'accAddr' x/delegation/keeper

Length of output: 932

x/delegation/client/cli/tx_delegation_native.go (1)

16-46: Command structure and error handling look good.

The structure of the CmdDelagateNativeToken command and its error handling are well implemented. The usage of sdkmath for amount validation and the comprehensive error messages enhance the robustness of the command.

x/delegation/types/msg.go (1)

29-41: Verify the integration and usage of the new message type MsgDelegation.

Ensure that the new message type MsgDelegation is properly integrated and used throughout the system. It's important to check that the ValidateBasic method is called whenever the message is created to ensure data integrity.

Verification successful

The MsgDelegation message type is properly integrated and its ValidateBasic method is called to ensure data integrity.

  • x/delegation/client/cli/tx_delegation_native.go: The ValidateBasic method is called to validate MsgDelegation.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the integration and usage of the new message type `MsgDelegation`.

# Test: Search for the message type usage and the `ValidateBasic` method call. Expect: Proper integration and validation calls.
rg --type go -A 5 $'MsgDelegation' --exec rg 'ValidateBasic' {}

Length of output: 471


Script:

#!/bin/bash
# Step 1: Search for the usage of MsgDelegation and list the files.
rg --type go 'MsgDelegation' -l > msg_delegation_usage_files.txt

# Step 2: Search for the ValidateBasic method call within those files.
while IFS= read -r file; do
    echo "Searching in $file"
    rg 'ValidateBasic' "$file"
done < msg_delegation_usage_files.txt

Length of output: 1352

x/assets/keeper/keeper.go (1)

13-27: Review of Keeper Struct and NewKeeper Constructor

  • Architecture: The addition of BankKeeper and delegationKeeper to the Keeper struct is consistent with dependency injection principles, which is good for modularity and testing.
  • Best Practices: The constructor NewKeeper correctly initializes the Keeper struct with provided dependencies, ensuring that all components are properly set up for use.
  • Maintainability: The clear separation of concerns and encapsulation of dependencies within the Keeper struct enhances maintainability.
x/delegation/keeper/delegation_op_test.go (1)

Line range hint 69-452: Comprehensive Review of Delegation Test Cases

  • Correctness: The tests cover both regular and native token delegations, ensuring that the new functionality is properly verified.
  • Logic: The tests follow a logical flow of preparing, executing, and verifying the outcomes of delegation and undelegation actions.
  • Maintainability: The use of descriptive function names and structured test cases enhances maintainability.
  • Performance: Consider mocking external dependencies to speed up the tests, especially if running against live environments.
  • Best Practices: The tests are well-structured and provide good coverage of the new functionalities introduced in the PR.

x/delegation/client/cli/tx.go Outdated Show resolved Hide resolved
x/delegation/keeper/msg_server.go Outdated Show resolved Hide resolved
x/assets/keeper/staker_asset.go Outdated Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between dc1d9ef and 0c9d0f0.

Files selected for processing (1)
  • x/delegation/keeper/delegation_op_test.go (7 hunks)
Files skipped from review as they are similar to previous changes (1)
  • x/delegation/keeper/delegation_op_test.go

app/app.go Outdated
app.StakingKeeper.OperatorHooks(),
)

(&app.EpochsKeeper).SetHooks(
app.EpochsKeeper.SetHooks(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When fixing conflicts use

epochstypes.NewMultiEpochHooks(
			app.StakingKeeper.EpochsHooks(), // at this point, the order is irrelevant.
			app.ExomintKeeper.EpochsHooks(), // however, this may change once we have distribution
		),

x/assets/keeper/expected_keepers.go Show resolved Hide resolved
x/assets/keeper/staker_asset.go Outdated Show resolved Hide resolved
x/assets/types/general.go Outdated Show resolved Hide resolved
x/assets/keeper/staker_asset.go Outdated Show resolved Hide resolved
x/delegation/client/cli/tx_delegation_native.go Outdated Show resolved Hide resolved
x/delegation/client/cli/tx_delegation_native.go Outdated Show resolved Hide resolved
x/delegation/client/cli/tx_delegation_native.go Outdated Show resolved Hide resolved
x/delegation/client/cli/tx_delegation_native.go Outdated Show resolved Hide resolved
x/delegation/keeper/msg_server.go Outdated Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 0c9d0f0 and d2f8f23.

Files ignored due to path filters (1)
  • x/delegation/types/tx.pb.go is excluded by !**/*.pb.go
Files selected for processing (11)
  • proto/exocore/delegation/v1/tx.proto (2 hunks)
  • x/assets/keeper/bank.go (1 hunks)
  • x/assets/keeper/staker_asset.go (2 hunks)
  • x/delegation/client/cli/tx.go (1 hunks)
  • x/delegation/client/cli/tx_delegation_native.go (1 hunks)
  • x/delegation/keeper/keeper.go (4 hunks)
  • x/delegation/keeper/msg_server.go (1 hunks)
  • x/delegation/keeper/share.go (2 hunks)
  • x/delegation/types/msg.go (2 hunks)
  • x/reward/keeper/claim_reward.go (1 hunks)
  • x/slash/keeper/execute_slash.go (6 hunks)
Files skipped from review as they are similar to previous changes (4)
  • x/assets/keeper/staker_asset.go
  • x/delegation/client/cli/tx_delegation_native.go
  • x/delegation/keeper/msg_server.go
  • x/delegation/types/msg.go
Additional comments not posted (4)
x/delegation/client/cli/tx.go (1)

21-23: Addition of CmdDelegate() and CmdUndelegate() commands to CLI

The addition of these commands is consistent with the PR's objective to enhance native token delegation functionality.

x/delegation/keeper/keeper.go (2)

Line range hint 24-44: Integration of bankKeeper into Keeper struct

The addition of bankKeeper to the Keeper struct is a crucial development, enhancing the module's ability to interact with banking operations directly. This change supports the PR's objectives related to asset management and delegation operations.


68-70: Addition of Logger Method to Keeper

The new Logger method enhances debugging and logging capabilities by providing a logger tied to the module's context. This is a beneficial addition for maintaining clarity and traceability in the module's operations.

proto/exocore/delegation/v1/tx.proto (1)

Line range hint 62-124: Modifications in tx.proto for Delegation Functionality

The changes in the protobuf definitions, including the use of repeated KeyValue instead of a map and the reordering of fields, are significant. These modifications improve the predictability and consistency of data serialization, which is crucial for blockchain operations. The addition of asset_id as a field with a custom name directive enhances clarity and specificity in message structures.

Comment on lines +143 to +151
// TODO: there should be a reward pool to be transferred from for native tokens' reward, don't update staker-asset-info, just transfer exo-native-token:pool->staker or handled by validators since the reward would be transferred to validators directly.
if assetID != types.NativeAssetID {
err := k.assetsKeeper.UpdateStakerAssetState(ctx, stakeID, assetID, changeAmount)
if err != nil {
return err
}
if err = k.assetsKeeper.UpdateStakingAssetTotalAmount(ctx, assetID, event.OpAmount); err != nil {
return err
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Conditional Logic for Native Tokens in RewardForWithdraw

The conditional logic introduced to handle rewards for native tokens separately seems appropriate given the context of native token management. However, the comment on line 143 suggests that there might be a need for a reward pool transfer mechanism which isn't implemented here.

  • Ensure that the logic for handling native tokens aligns with the overall system's token management strategy.
  • Consider implementing or clarifying the reward pool transfer mechanism as hinted in the TODO comment.

Comment on lines 194 to 208
// dont't create stakerasset info for native token.
// TODO: do we need to do any other process for native token 'else{}' ?
if assetID != assetstypes.NativeAssetID {
changeAmount := assetstypes.DeltaStakerSingleAsset{
TotalDepositAmount: event.OpAmount.Neg(),
}
err := k.assetsKeeper.UpdateStakerAssetState(ctx, stakeID, assetID, changeAmount)
if err != nil {
return err
}
if err = k.assetsKeeper.UpdateStakingAssetTotalAmount(ctx, assetID, event.OpAmount.Neg()); err != nil {
return err
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Handling of Native Tokens in Slash Function

The conditional logic to not create staker asset info for native tokens is a significant change. This aligns with the PR's focus on native token management but raises a few concerns:

  • The comment on line 195 asks whether additional processes are needed for native tokens. This needs clarification.
  • Ensure that the skipping of asset state updates for native tokens does not lead to inconsistencies in the system's state management.

Comment on lines 217 to 233
// don't update staker asset info for exo-native-token
if assetID != assetstypes.NativeAssetID {
// todo: TotalDepositAmount might be influenced by slash and precision loss,
// consider removing it, it can be recalculated from the share for RPC query.
err = k.assetsKeeper.UpdateStakerAssetState(ctx, stakerID, assetID, assetstype.DeltaStakerSingleAsset{
WaitUnbondingAmount: removeToken,
})
if err != nil {
return removeToken, err
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Conditional Logic for Native Tokens in RemoveShare Function

The introduction of conditional logic to skip updating staker asset state for native tokens is critical for the system's handling of these assets. However, the comment on line 220 suggests reconsidering the calculation of TotalDepositAmount. This might indicate potential issues with precision loss or other calculation inaccuracies.

  • Verify that skipping the update of staker asset state for native tokens is consistent with other parts of the system.
  • Address the concern raised about TotalDepositAmount to ensure accurate financial calculations.

Comment on lines 50 to 56
// don't update staker info for exo-native-token
// TODO: do we need additional process for exo-native-token ?
if assetID != assetstypes.NativeAssetID {
// update asset state of the specified staker
err = k.UpdateStakerAssetState(ctx, stakeID, assetID, changeAmount)
if err != nil {
return errorsmod.Wrapf(err, "stakeID:%s assetID:%s", stakeID, assetID)
}

// update total amount of the deposited asset
err = k.UpdateStakingAssetTotalAmount(ctx, assetID, actualOpAmount)
if err != nil {
return errorsmod.Wrapf(err, "assetID:%s", assetID)
// update total amount of the deposited asset
err = k.UpdateStakingAssetTotalAmount(ctx, assetID, actualOpAmount)
if err != nil {
return errorsmod.Wrapf(err, "assetID:%s", assetID)
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Conditional Logic for exo-native-token in PerformDepositOrWithdraw

The addition of a condition to skip updating staker info for exo-native-token is a significant change. This logic ensures that operations specific to the native token are handled differently, which is crucial given its unique role in the ecosystem.

However, the TODO comment indicates uncertainty about whether additional processes are needed for exo-native-token. It's important to address this to ensure that all necessary operations for the native token are correctly implemented.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between d2f8f23 and cfb320e.

Files selected for processing (3)
  • x/assets/keeper/staker_asset.go (2 hunks)
  • x/assets/types/general.go (1 hunks)
  • x/delegation/client/cli/tx_delegation_native.go (1 hunks)
Files skipped from review as they are similar to previous changes (3)
  • x/assets/keeper/staker_asset.go
  • x/assets/types/general.go
  • x/delegation/client/cli/tx_delegation_native.go

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Outside diff range, codebase verification and nitpick comments (4)
x/assets/client/cli/tx.go (3)

Line range hint 26-35:
Re-add the validation step for robustness.

The removal of msg.ValidateBasic() can lead to the processing of invalid messages, reducing the function's robustness. It's recommended to re-add the validation step to ensure basic validation of the msg object.

+			if err := msg.ValidateBasic(); err != nil {
+				return err
+			}

Line range hint 52-73:
Re-add the validation step for robustness.

The removal of msg.ValidateBasic() can lead to the processing of invalid messages, reducing the function's robustness. It's recommended to re-add the validation step to ensure basic validation of the msg object.

+			if err := msg.ValidateBasic(); err != nil {
+				return err
+			}

Line range hint 92-119:
Re-add the validation step for robustness.

The removal of msg.ValidateBasic() can lead to the processing of invalid messages, reducing the function's robustness. It's recommended to re-add the validation step to ensure basic validation of the msg object.

+			if err := msg.ValidateBasic(); err != nil {
+				return err
+			}
x/slash/keeper/execute_slash.go (1)

13-15: Remove commented import.

The commented import statement should be removed to keep the code clean.

-	//	"github.com/ExocoreNetwork/exocore/x/assets/types"
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between cfb320e and a95751b.

Files ignored due to path filters (1)
  • x/delegation/types/tx.pb.go is excluded by !**/*.pb.go
Files selected for processing (10)
  • proto/exocore/delegation/v1/tx.proto (3 hunks)
  • x/assets/client/cli/tx.go (3 hunks)
  • x/assets/keeper/expected_keepers.go (1 hunks)
  • x/assets/keeper/staker_asset.go (2 hunks)
  • x/assets/keeper/staker_asset_test.go (1 hunks)
  • x/delegation/client/cli/tx_delegation_native.go (1 hunks)
  • x/delegation/keeper/keeper.go (4 hunks)
  • x/delegation/keeper/share.go (1 hunks)
  • x/delegation/types/msg.go (2 hunks)
  • x/slash/keeper/execute_slash.go (6 hunks)
Additional comments not posted (19)
x/assets/keeper/expected_keepers.go (1)

1-11: LGTM! But verify the usage of the new interface.

The code changes are approved.

However, ensure that the new delegationKeeper interface is correctly used in the codebase.

Verification successful

The new delegationKeeper interface is correctly used in the codebase.

The GetDelegationInfo method from the delegationKeeper interface is utilized in various parts of the code, confirming its proper integration.

  • x/delegation/keeper/grpc_query.go
  • x/assets/keeper/staker_asset.go
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of the new `delegationKeeper` interface.

# Test: Search for the interface usage. Expect: Occurrences of the new interface.
rg --type go -A 5 $'delegationKeeper'

Length of output: 9349


Script:

#!/bin/bash
# Description: Verify the usage of the `GetDelegationInfo` method from the `delegationKeeper` interface.

# Test: Search for the method usage. Expect: Occurrences of the method call.
rg --type go -A 5 $'GetDelegationInfo'

Length of output: 4816

x/delegation/types/msg.go (2)

66-79: LGTM! But verify the usage of the new function NewMsgUndelegation.

The code changes are approved.

However, ensure that the new NewMsgUndelegation function is correctly used in the codebase.

Verification successful

The function NewMsgUndelegation is correctly used in the codebase.

  • The function NewMsgUndelegation is utilized in x/delegation/client/cli/tx_delegation_native.go.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of the new `NewMsgUndelegation` function.

# Test: Search for the function usage. Expect: Occurrences of the new function.
rg --type go -A 5 $'NewMsgUndelegation'

Length of output: 991


27-40: LGTM! But verify the usage of the new function NewMsgDelegation.

The code changes are approved.

However, ensure that the new NewMsgDelegation function is correctly used in the codebase.

x/delegation/client/cli/tx_delegation_native.go (2)

1-39: LGTM! But verify the usage of the CLI command CmdDelegate.

The code changes are approved.

However, ensure that the new CmdDelegate command is correctly used in the codebase.

Verification successful

The CmdDelegate command is correctly used in the codebase.

  • The command is registered as a subcommand of txCmd in x/delegation/client/cli/tx.go.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of the new `CmdDelegate` command.

# Test: Search for the command usage. Expect: Occurrences of the new command.
rg --type go -A 5 $'CmdDelegate'

Length of output: 829


Script:

#!/bin/bash
# Extract the relevant section from tx.go to verify the usage of CmdDelegate.
rg --type go -A 10 -B 10 $'CmdDelegate' x/delegation/client/cli/tx.go

Length of output: 425


41-66: LGTM! But verify the usage of the CLI command CmdUndelegate.

The code changes are approved.

However, ensure that the new CmdUndelegate command is correctly used in the codebase.

x/delegation/keeper/keeper.go (3)

19-23: LGTM! The new fields are correctly added to the Keeper struct.

The addition of accountKeeper and bankKeeper fields enhances the Keeper's functionality by allowing it to manage account and bank-related operations.


33-43: LGTM! The NewKeeper constructor function is correctly updated.

The function now accepts accountKeeper and bankKeeper parameters and initializes the corresponding fields in the Keeper struct.


67-69: LGTM! The Logger method is a valuable addition.

The method provides a structured logging mechanism, enhancing the traceability of logs associated with the delegation module.

proto/exocore/delegation/v1/tx.proto (4)

54-54: LGTM! The change to repeated KeyValue is appropriate.

Using repeated KeyValue instead of a map ensures order consistency and avoids issues with deserialization in Golang.


59-62: LGTM! The changes to MsgDelegation are appropriate.

The introduction of the asset_id field and reordering of fields enhance the clarity and functionality of the message.


113-114: LGTM! The changes to MsgUndelegation are appropriate.

The introduction of the asset_id field and reordering of fields enhance the clarity and functionality of the message.


Line range hint 1-1:
LGTM! The removal of DelegationApproveInfo is appropriate.

The removal simplifies the delegation process and likely integrates its functionality elsewhere.

x/assets/keeper/staker_asset.go (1)

32-37: Ensure error handling for native asset info retrieval.

The added logic correctly retrieves native asset information. However, ensure that the error handling aligns with the overall error management strategy.

x/assets/keeper/staker_asset_test.go (1)

84-84: Verify the new staker ID format.

The staker ID format has been updated to use "0x0". Ensure this change aligns with the new requirements and verify its impact on subsequent logic.

x/slash/keeper/execute_slash.go (4)

47-56: Ensure proper handling of action types.

The action types have been updated to use assetstypes. Ensure all possible action types are handled correctly.


83-85: Verify operator address handling.

The operator address is now handled as assetstypes.ExoCoreOperatorAddrLength. Ensure this change is consistent with the new requirements.


105-105: Verify cross-chain operation amount length.

The cross-chain operation amount length is now handled as assetstypes.CrossChainOpAmountLength. Ensure this change is consistent with the new requirements.


189-208: Clarify handling of native tokens in slashing logic.

The logic for handling native tokens during slashing events is added. Ensure this logic is consistent with the overall strategy for native token management.

Verification successful

Clarify handling of native tokens in slashing logic.

The handling of native tokens in the slashing logic in x/slash/keeper/execute_slash.go is consistent with the overall strategy for native token management across the codebase. The pattern of checking for NativeAssetID and applying specific logic is consistently followed.

  • x/slash/keeper/execute_slash.go
  • x/reward/keeper/claim_reward.go
  • x/delegation/keeper/msg_server.go
  • x/assets/keeper/staker_asset.go
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the handling of native tokens in slashing logic.

# Test: Search for the usage of `NativeAssetID` in the slashing logic.
rg --type go 'NativeAssetID' -A 5

Length of output: 5310


Script:

#!/bin/bash
# Description: Verify the handling of native tokens in slashing logic across the codebase.

# Search for the usage of `NativeAssetID` in all Go files to understand the handling logic.
rg --type go 'NativeAssetID' -A 10 -B 10

Length of output: 15613

x/delegation/keeper/share.go (1)

216-217: Verify consistency of the conditional check.

Ensure that skipping the update of staker asset state for native tokens is consistent with other parts of the system.

Verification successful

Verified consistency of the conditional check.

The conditional check to skip updating the staker asset state for native tokens is consistent with other parts of the system.

  • x/slash/keeper/execute_slash.go
  • x/reward/keeper/claim_reward.go
  • x/delegation/keeper/msg_server.go
  • x/delegation/keeper/abci.go
  • x/delegation/keeper/cross_chain_tx_process.go
  • x/assets/keeper/staker_asset.go
  • x/assets/keeper/bank.go
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify consistency of the conditional check for native tokens.

# Test: Search for similar conditional checks in the codebase. Expect: Consistent handling of native tokens.
rg --type python -A 5 $'NativeAssetID'

Length of output: 68


Script:

#!/bin/bash
# Description: Verify consistency of the conditional check for native tokens.

# Test: Search for similar conditional checks in Go files. Expect: Consistent handling of native tokens.
rg --type go -A 5 $'NativeAssetID'

Length of output: 5310

Comment on lines +218 to +227
// todo: TotalDepositAmount might be influenced by slash and precision loss,
// consider removing it, it can be recalculated from the share for RPC query.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Address the TODO comment regarding TotalDepositAmount.

The comment suggests potential issues with precision loss or other calculation inaccuracies. Consider addressing this in a future update.

Do you want me to open a GitHub issue to track this task?

x/assets/keeper/staker_asset.go Outdated Show resolved Hide resolved
@leonz789 leonz789 force-pushed the develop-delegation-nativetoken branch from a95751b to a1aed48 Compare September 3, 2024 07:53
x/assets/keeper/staker_asset.go Dismissed Show dismissed Hide dismissed
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

Outside diff range, codebase verification and nitpick comments (2)
x/assets/client/cli/tx.go (1)

Line range hint 45-46: Validation step should not be removed.

Removing the validation step for the msg object is concerning because it could allow invalid messages to be processed. The msg.ValidateBasic() check serves as an important safeguard to catch errors before the transaction is executed.

Please retain the validation step:

  msg := &assetstype.MsgUpdateParams{
    Authority: sender.String(),
    Params: assetstype.Params{
      ExocoreLzAppAddress:    args[0],  
      ExocoreLzAppEventTopic: args[1],
    },
  }
  
+ if err := msg.ValidateBasic(); err != nil {
+   return err
+ }

  return tx.GenerateOrBroadcastTxCLI(cliCtx, cmd.Flags(), msg)
x/assets/keeper/staker_asset.go (1)

42-76: Approved with a suggestion for optimization.

The code changes to handle the retrieval of native asset information for a staker are implemented correctly and align with the PR objectives. The error handling for address decoding has been improved as per the past review comment.

Suggestion: If the number of delegation records is expected to be large, consider optimizing the loop at line range 63-74 to improve performance. One approach could be to use goroutines to process the records concurrently.

Tools
GitHub Check: CodeQL

[warning] 63-74: Iteration over map
Iteration over map may be a possible source of non-determinism

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between a95751b and a1aed48.

Files ignored due to path filters (1)
  • x/delegation/types/tx.pb.go is excluded by !**/*.pb.go
Files selected for processing (26)
  • app/app.go (9 hunks)
  • proto/exocore/delegation/v1/tx.proto (3 hunks)
  • testutil/utils.go (1 hunks)
  • x/assets/client/cli/tx.go (1 hunks)
  • x/assets/keeper/bank.go (1 hunks)
  • x/assets/keeper/expected_keepers.go (1 hunks)
  • x/assets/keeper/keeper.go (1 hunks)
  • x/assets/keeper/staker_asset.go (2 hunks)
  • x/assets/keeper/staker_asset_test.go (1 hunks)
  • x/assets/types/expected_keepers.go (1 hunks)
  • x/assets/types/general.go (1 hunks)
  • x/delegation/client/cli/tx.go (1 hunks)
  • x/delegation/client/cli/tx_delegation_native.go (1 hunks)
  • x/delegation/keeper/abci.go (4 hunks)
  • x/delegation/keeper/delegation.go (1 hunks)
  • x/delegation/keeper/delegation_op_test.go (7 hunks)
  • x/delegation/keeper/delegation_state.go (1 hunks)
  • x/delegation/keeper/keeper.go (4 hunks)
  • x/delegation/keeper/msg_server.go (1 hunks)
  • x/delegation/keeper/setup_test.go (2 hunks)
  • x/delegation/keeper/share.go (1 hunks)
  • x/delegation/keeper/un_delegation_state.go (1 hunks)
  • x/delegation/types/cross_chain_params.go (1 hunks)
  • x/delegation/types/expected_keepers.go (1 hunks)
  • x/delegation/types/general.go (1 hunks)
  • x/delegation/types/msg.go (2 hunks)
Files skipped from review due to trivial changes (2)
  • testutil/utils.go
  • x/delegation/keeper/un_delegation_state.go
Additional context used
Learnings (1)
x/delegation/keeper/msg_server.go (1)
Learnt from: MaxMustermann2
PR: ExocoreNetwork/exocore#127
File: x/delegation/keeper/msg_server.go:17-46
Timestamp: 2024-07-16T05:32:21.301Z
Learning: The `msg` object in the `DelegateAssetToOperator` function is validated using `msg.ValidateBasic` before it reaches the function, ensuring that all addresses are correct and allowing the safe use of `sdk.MustAccAddressFromBech32`.
GitHub Check: CodeQL
x/delegation/keeper/abci.go

[warning] 76-76: Panic in BeginBock or EndBlock consensus methods
path flow from Begin/EndBlock to a panic call


[warning] 76-76: Panic in BeginBock or EndBlock consensus methods
Possible panics in BeginBock- or EndBlock-related consensus methods could cause a chain halt


[warning] 84-84: Panic in BeginBock or EndBlock consensus methods
path flow from Begin/EndBlock to a panic call


[warning] 84-84: Panic in BeginBock or EndBlock consensus methods
Possible panics in BeginBock- or EndBlock-related consensus methods could cause a chain halt

x/assets/keeper/staker_asset.go

[warning] 63-74: Iteration over map
Iteration over map may be a possible source of non-determinism

GitHub Check: break-check
proto/exocore/delegation/v1/tx.proto

[failure] 54-54:
Field "2" on message "DelegationIncOrDecInfo" changed type from "exocore.delegation.v1.DelegationIncOrDecInfo.PerOperatorAmountsEntry" to "exocore.delegation.v1.KeyValue".


[failure] 60-60:
Field "1" with name "asset_id" on message "MsgDelegation" changed option "json_name" from "baseInfo" to "assetId".


[failure] 60-60:
Field "1" on message "MsgDelegation" changed type from "message" to "string".


[failure] 60-60:
Field "1" on message "MsgDelegation" changed name from "base_info" to "asset_id".


[failure] 62-62:
Field "2" with name "base_info" on message "MsgDelegation" changed option "json_name" from "approvedInfo" to "baseInfo".


[failure] 62-62:
Field "2" on message "MsgDelegation" changed type from "exocore.delegation.v1.DelegationApproveInfo" to "exocore.delegation.v1.DelegationIncOrDecInfo".


[failure] 62-62:
Field "2" on message "MsgDelegation" changed name from "approved_info" to "base_info".


[failure] 113-113:
Field "1" with name "asset_id" on message "MsgUndelegation" changed option "json_name" from "baseInfo" to "assetId".

Additional comments not posted (47)
x/assets/types/expected_keepers.go (1)

12-14: LGTM!

The new BankKeeper interface is well-defined and follows good practices:

  • It abstracts the interaction with the bank module, promoting modularity.
  • The GetBalance method signature is appropriate for retrieving the balance of an account for a specific denomination.

The code changes are approved.

x/delegation/types/general.go (1)

5-10: LGTM!

The code changes are approved for the following reasons:

  • The constants improve the clarity and organization of the code by providing semantic names for different types of token pools.
  • The comment serves as a helpful reminder of the current limitations and the reasoning behind the naming of DelegatedPoolName.
  • The constants are declared correctly and follow the naming conventions.
x/assets/keeper/expected_keepers.go (1)

1-11: LGTM!

The code changes are approved.

The existing review comments discuss the placement of the interface definition and the reason for placing it in the keeper package. The comment added by the developer at line 8 addresses the concern raised in the previous review comments. Therefore, no further comments are necessary.

x/delegation/client/cli/tx.go (1)

21-23: LGTM!

The code changes are approved for the following reasons:

  • The CmdDelegate and CmdUndelegate commands are correctly added to the txCmd command group.
  • The command names match their intended functionality, as described in the PR objectives and the AI-generated summary.
  • The code changes are consistent with the PR objectives and the AI-generated summary.
x/delegation/keeper/setup_test.go (2)

8-8: LGTM!

The code changes are approved.


23-23: LGTM!

The code changes are approved.

x/delegation/types/cross_chain_params.go (1)

22-42: LGTM!

The constructor function NewDelegationOrUndelegationParams is correctly implemented and follows the best practices for constructor functions in Go. It takes several parameters that correspond to the fields of the DelegationOrUndelegationParams struct and returns a pointer to a newly created instance of the struct. This function improves the usability of the struct by providing a clear and concise way to instantiate it, thereby enhancing code readability and maintainability.

x/delegation/types/msg.go (2)

28-40: LGTM!

The code changes are approved.


67-79: LGTM!

The code changes are approved.

x/assets/keeper/bank.go (1)

50-63: The existing comment on the changes is still valid:

Conditional Logic for exo-native-token in PerformDepositOrWithdraw

The addition of a condition to skip updating staker info for exo-native-token is a significant change. This logic ensures that operations specific to the native token are handled differently, which is crucial given its unique role in the ecosystem.

However, the TODO comment indicates uncertainty about whether additional processes are needed for exo-native-token. It's important to address this to ensure that all necessary operations for the native token are correctly implemented.

x/delegation/client/cli/tx_delegation_native.go (2)

16-39: LGTM!

The code changes are approved.


41-66: LGTM!

The code changes are approved.

x/delegation/keeper/keeper.go (4)

19-23: LGTM!

The addition of accountKeeper and bankKeeper fields to the Keeper struct enhances its capability to manage accounts and banking operations within the delegation module.


33-34: LGTM!

The updated NewKeeper function signature ensures that instances of Keeper can be initialized with the necessary dependencies for account and banking management.


42-43: LGTM!

The initialization of accountKeeper and bankKeeper fields in the NewKeeper function is consistent with the updated Keeper struct and function signature.


67-69: LGTM!

The new Logger method provides a context-aware logging interface that includes the module name, allowing for better tracking and debugging of operations related to the delegation module.

x/assets/keeper/keeper.go (2)

16-17: LGTM!

The changes to the Keeper struct are approved. The addition of the bk and dk fields will allow the Keeper to interact with the bank and delegation modules, respectively, to perform operations related to asset management and delegation. This is consistent with the PR summary.


24-25: LGTM!

The changes to the NewKeeper constructor function are approved. The addition of the bk and dk parameters and their use in initializing the corresponding fields of the Keeper struct are necessary and consistent with the changes to the Keeper struct.

Also applies to: 31-32

x/delegation/types/expected_keepers.go (2)

57-61: LGTM!

The BankKeeper interface is well-defined and serves a clear purpose. The method names and parameters are self-explanatory, and the interface is correctly placed in the types package.


63-65: LGTM!

The AccountKeeper interface is well-defined and serves a clear purpose. The method name and parameters are self-explanatory, and the interface is correctly placed in the types package.

x/delegation/keeper/abci.go (2)

72-86: LGTM!

The changes enhance the functionality of the undelegation process by introducing a new flow for handling native assets. If the record.AssetID matches assetstypes.NativeAssetID, it parses the StakerID, retrieves the corresponding address, and undelegates coins directly to the account. If not matched, it falls back to the previous method of updating the staker's asset state using assetstypes.DeltaStakerSingleAsset. The changes look good.

Tools
GitHub Check: CodeQL

[warning] 76-76: Panic in BeginBock or EndBlock consensus methods
path flow from Begin/EndBlock to a panic call


[warning] 76-76: Panic in BeginBock or EndBlock consensus methods
Possible panics in BeginBock- or EndBlock-related consensus methods could cause a chain halt


[warning] 84-84: Panic in BeginBock or EndBlock consensus methods
path flow from Begin/EndBlock to a panic call


[warning] 84-84: Panic in BeginBock or EndBlock consensus methods
Possible panics in BeginBock- or EndBlock-related consensus methods could cause a chain halt


76-76: The previous review comments on panic warnings at line ranges 76-76 and 84-84 are still valid and applicable to the current code. Skipping generating similar comments.

Also applies to: 84-84

Tools
GitHub Check: CodeQL

[warning] 76-76: Panic in BeginBock or EndBlock consensus methods
path flow from Begin/EndBlock to a panic call


[warning] 76-76: Panic in BeginBock or EndBlock consensus methods
Possible panics in BeginBock- or EndBlock-related consensus methods could cause a chain halt

x/assets/types/general.go (4)

10-10: The import path has been correctly updated based on the previous review comment.


16-18: LGTM!

The code changes are approved.


19-20: LGTM!

The code changes are approved. The modification to use utils.BaseDenom enhances the flexibility of the asset denomination.


21-23: LGTM!

The code changes are approved. The commented-out lines suggest a cleanup of unused constants.

proto/exocore/delegation/v1/tx.proto (4)

59-60: LGTM: The addition of the asset_id field is approved.

The asset_id field has been added to the MsgDelegation message as the first field, with a custom name specified for serialization. This addition enhances the clarity and specificity of the delegation operation by explicitly identifying the asset.

Tools
GitHub Check: break-check

[failure] 60-60:
Field "1" with name "asset_id" on message "MsgDelegation" changed option "json_name" from "baseInfo" to "assetId".


[failure] 60-60:
Field "1" on message "MsgDelegation" changed type from "message" to "string".


[failure] 60-60:
Field "1" on message "MsgDelegation" changed name from "base_info" to "asset_id".


62-62: No action required: The field order change is acceptable.

The base_info field in the MsgDelegation message has been moved to the second position. This change in the field order does not affect the functionality of the message.

Tools
GitHub Check: break-check

[failure] 62-62:
Field "2" with name "base_info" on message "MsgDelegation" changed option "json_name" from "approvedInfo" to "baseInfo".


[failure] 62-62:
Field "2" on message "MsgDelegation" changed type from "exocore.delegation.v1.DelegationApproveInfo" to "exocore.delegation.v1.DelegationIncOrDecInfo".


[failure] 62-62:
Field "2" on message "MsgDelegation" changed name from "approved_info" to "base_info".


113-114: LGTM: The addition of the asset_id field is approved.

The asset_id field has been added to the MsgUndelegation message as the first field, with a custom name specified for serialization. This addition enhances the clarity and specificity of the undelegation operation by explicitly identifying the asset.

No action required: The field order change is acceptable.

The base_info field in the MsgUndelegation message has been moved to the second position. This change in the field order does not affect the functionality of the message.

Tools
GitHub Check: break-check

[failure] 113-113:
Field "1" with name "asset_id" on message "MsgUndelegation" changed option "json_name" from "baseInfo" to "assetId".


54-54: Verify the impact of the change from a map to a list structure.

The per_operator_amounts field has been changed from a map<string, ValueField> to a repeated KeyValue. Ensure that this change does not break any existing code that relies on the previous map structure.

Run the following script to verify the usage of the per_operator_amounts field:

LGTM: The addition of the gogoproto.nullable option is approved.

Setting the gogoproto.nullable option to false for the per_operator_amounts field enforces stricter data integrity by indicating that this field cannot be null.

Tools
GitHub Check: break-check

[failure] 54-54:
Field "2" on message "DelegationIncOrDecInfo" changed type from "exocore.delegation.v1.DelegationIncOrDecInfo.PerOperatorAmountsEntry" to "exocore.delegation.v1.KeyValue".

x/assets/keeper/staker_asset.go (1)

32-37: LGTM!

The code changes to retrieve and add the native asset information for a staker are approved.

x/assets/keeper/staker_asset_test.go (1)

84-84: Verify the reason for the change in the stakerID format.

The change alters the format of the stakerID variable by concatenating suite.Address with "0x0" instead of "0". This suggests a shift in how staker IDs are represented.

Please confirm the reason for this change and ensure that it aligns with the new standard or format for identifiers in the system. Also, verify that this change is consistently applied across the codebase.

x/delegation/keeper/msg_server.go (3)

17-72: Approved: The DelegateAssetToOperator function has been updated to handle native token delegation.

The changes to the DelegateAssetToOperator function align with the PR objectives and introduce several improvements:

  • The function now checks if the asset being delegated is the native asset and returns an appropriate error if not, ensuring that only native tokens are supported.
  • The use of the newDelegationParams helper function improves code readability and maintainability by encapsulating the logic for generating delegation parameters.
  • The error handling and logging statements provide better visibility into the delegation process, making it easier to identify and debug issues.

Overall, the changes enhance the functionality and maintainability of the delegation process.


74-104: Approved: The UndelegateAssetFromOperator function has been updated to handle native token undelegation.

The changes to the UndelegateAssetFromOperator function introduce several improvements:

  • The function now checks if the asset being undelegated is the native asset and returns an appropriate error if not, ensuring that only native tokens are supported.
  • The use of the newDelegationParams helper function improves code reusability and maintainability by leveraging the same logic for generating undelegation parameters as the delegation function.
  • The error handling ensures that any issues during the undelegation process are propagated appropriately.

These changes align with the PR objectives and enhance the functionality and maintainability of the undelegation process.


128-145: Approved: The newDelegationParams helper function improves code reusability and maintainability.

The addition of the newDelegationParams helper function is a positive change that offers the following benefits:

  • It encapsulates the logic for generating delegation or undelegation parameters, reducing code duplication and improving maintainability.
  • It accepts the necessary base information and asset details as parameters, making it flexible and reusable across different scenarios.
  • It returns a slice of DelegationOrUndelegationParams pointers, which aligns with the expected input for the DelegateTo and UndelegateFrom functions.

The use of sdk.MustAccAddressFromBech32 to convert the staker and operator addresses is safe based on the learnings from the previous review, as the input addresses are assumed to be valid at this point.

Overall, the introduction of this helper function enhances the code quality and maintainability of the delegation and undelegation processes.

x/delegation/keeper/share.go (1)

224-233: Conditional logic for handling native tokens.

The introduction of conditional logic to skip updating staker asset state for native tokens is a critical change for differentiating the handling of these assets.

Please verify that skipping the update of staker asset state for native tokens is consistent with the behavior in other parts of the system.

x/delegation/keeper/delegation.go (2)

41-59: LGTM!

The code changes correctly handle the delegation logic for non-native assets by:

  • Checking if the asset is non-native.
  • Retrieving the staker's asset information.
  • Verifying if the withdrawable amount is sufficient for delegation.
  • Updating the staker's asset state if the delegation is valid.

The changes are approved.


60-64: LGTM!

The code segment correctly handles the delegation logic for native assets by:

  • Creating a coin object representing the delegation amount.
  • Transferring the delegation amount from the staker's account to the delegated pool.

The changes are approved.

x/delegation/keeper/delegation_state.go (1)

170-170: LGTM!

The code change enhances the clarity of the error handling by directly using the Wrapf method on the custom error delegationtype.ErrNoKeyInTheStore. This allows including the key that was not found in the store in the error message.

x/delegation/keeper/delegation_op_test.go (4)

70-84: LGTM!

The code changes are approved.


145-187: LGTM!

The code changes are approved.


251-308: LGTM!

The code changes are approved.


Line range hint 312-451: LGTM!

The code changes are approved.

app/app.go (4)

119-120: LGTM!

The code changes are approved. The vesting and vestingtypes imports are necessary for adding support for vesting accounts in the application.


260-260: LGTM!

The code change is approved. Adding the vesting module to the ModuleBasics variable is necessary for integrating the vesting functionality into the application.


292-294: LGTM!

The code changes are approved. Adding the module account permissions for the exomint, erc20, and delegation modules is necessary for the proper functioning of these modules.


551-560: LGTM!

The code changes are approved. Updating the AssetsKeeper and DelegationKeeper to take additional dependencies is necessary for their proper functioning within the application.

x/delegation/client/cli/tx_delegation_native.go Outdated Show resolved Hide resolved
@@ -34,8 +38,8 @@
continue
}*/

recordID := delegationtype.GetUndelegationRecordKey(record.BlockNumber, record.LzTxNonce, record.TxHash, record.OperatorAddr)
if k.GetUndelegationHoldCount(ctx, recordID) > 0 {
recordID := types.GetUndelegationRecordKey(record.BlockNumber, record.LzTxNonce, record.TxHash, record.OperatorAddr)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Refactor: Consolidate types under a single namespace.

The change renames the imported delegationtype to types and uses types.GetUndelegationRecordKey instead of delegationtype.GetUndelegationRecordKey. This consolidates types under a single namespace without introducing any functional changes.

x/delegation/keeper/abci.go Outdated Show resolved Hide resolved
x/delegation/keeper/abci.go Show resolved Hide resolved
}
}

//---
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

remove the commented code.

logger.Error("failed to get nonce", "error", err)
return nil, err
}
// // stakerAddr := sdk.MustAccAddressFromBech32(msg.BaseInfo.FromAddress).Bytes()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

remove the commented code.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

removed

x/delegation/keeper/msg_server.go Outdated Show resolved Hide resolved
@cloud8little
Copy link
Contributor

Test object: a1aed48
Tested all vesting type include continuous type, delayed type, and periodic type account, all these accounts are able to make delegation for the locked amount, but it requires spendable amount to pay for the transaction fee.

@cloud8little cloud8little added this to the Testnet V6 milestone Sep 10, 2024
@cloud8little cloud8little mentioned this pull request Sep 10, 2024
13 tasks
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Outside diff range, codebase verification and nitpick comments (3)
x/delegation/client/cli/tx_delegation_native.go (2)

18-18: Address the limitation mentioned in the TODO comment.

The TODO comment indicates that the command currently only supports native tokens. Consider expanding the support to other token types in future iterations to enhance the functionality of the command.


70-70: Improve the error message for the argument count check.

-  if len(args) != 3 {
-    return "", "", sdkmath.ZeroInt(), errors.New("3 arguments needed")
+  if len(args) != 3 {
+    return "", "", sdkmath.ZeroInt(), errors.New("exactly 3 arguments are required")
  }

The error message should clearly indicate that exactly 3 arguments are required for the command.

x/assets/keeper/staker_asset.go (1)

42-76: LGTM with a minor suggestion!

The new GetStakerSpecifiedAssetInfo function looks good overall and aligns with the PR objective to handle native assets. A few observations:

  • Consider adding more context to the error messages to improve debugging. For example:
-		if err != nil {
-			return nil, err
+		if err != nil {
+			return nil, errorsmod.Wrap(err, "failed to parse stakerID")
		}
  • The static analysis warning about iteration over map being a potential source of non-determinism is a false positive in this case. The order of iteration does not affect the correctness of the aggregated result.
Tools
GitHub Check: CodeQL

[warning] 63-74: Iteration over map
Iteration over map may be a possible source of non-determinism

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between a1aed48 and f34bb2c.

Files selected for processing (7)
  • proto/exocore/delegation/v1/tx.proto (3 hunks)
  • x/assets/keeper/staker_asset.go (2 hunks)
  • x/delegation/client/cli/tx_delegation_native.go (1 hunks)
  • x/delegation/keeper/abci.go (4 hunks)
  • x/delegation/keeper/msg_server.go (1 hunks)
  • x/delegation/types/errors.go (1 hunks)
  • x/delegation/types/msg.go (3 hunks)
Additional context used
GitHub Check: CodeQL
x/delegation/keeper/abci.go

[warning] 76-76: Panic in BeginBock or EndBlock consensus methods
Possible panics in BeginBock- or EndBlock-related consensus methods could cause a chain halt


[warning] 76-76: Panic in BeginBock or EndBlock consensus methods
path flow from Begin/EndBlock to a panic call


[warning] 84-84: Panic in BeginBock or EndBlock consensus methods
Possible panics in BeginBock- or EndBlock-related consensus methods could cause a chain halt


[warning] 84-84: Panic in BeginBock or EndBlock consensus methods
path flow from Begin/EndBlock to a panic call

x/assets/keeper/staker_asset.go

[warning] 63-74: Iteration over map
Iteration over map may be a possible source of non-determinism

GitHub Check: break-check
proto/exocore/delegation/v1/tx.proto

[failure] 54-54:
Field "2" on message "DelegationIncOrDecInfo" changed type from "exocore.delegation.v1.DelegationIncOrDecInfo.PerOperatorAmountsEntry" to "exocore.delegation.v1.KeyValue".


[failure] 60-60:
Field "1" with name "asset_id" on message "MsgDelegation" changed option "json_name" from "baseInfo" to "assetId".


[failure] 60-60:
Field "1" on message "MsgDelegation" changed type from "message" to "string".


[failure] 60-60:
Field "1" on message "MsgDelegation" changed name from "base_info" to "asset_id".


[failure] 62-62:
Field "2" with name "base_info" on message "MsgDelegation" changed option "json_name" from "approvedInfo" to "baseInfo".


[failure] 62-62:
Field "2" on message "MsgDelegation" changed type from "exocore.delegation.v1.DelegationApproveInfo" to "exocore.delegation.v1.DelegationIncOrDecInfo".


[failure] 62-62:
Field "2" on message "MsgDelegation" changed name from "approved_info" to "base_info".


[failure] 113-113:
Field "1" with name "asset_id" on message "MsgUndelegation" changed option "json_name" from "baseInfo" to "assetId".

Additional comments not posted (17)
x/delegation/types/errors.go (1)

82-85: LGTM!

The addition of ErrInvalidAssetID enhances the error handling capabilities of the module by allowing it to explicitly signal when an invalid asset ID is encountered, thereby improving the clarity and specificity of error reporting in the codebase.

x/delegation/types/msg.go (5)

22-23: LGTM!

The refactoring of the ValidateBasic method for MsgDelegation to utilize the new helper function validateDelegationInfo enhances code reusability and maintainability by reducing redundancy.


53-53: LGTM!

The refactoring of the ValidateBasic method for MsgUndelegation to utilize the new helper function validateDelegationInfo enhances code reusability and maintainability by reducing redundancy.


26-36: LGTM!

The addition of the NewMsgDelegation function encapsulates the delegation process within this constructor, improving clarity and ensuring that the MsgDelegation instance is properly initialized.


62-74: LGTM!

The addition of the NewMsgUndelegation function encapsulates the undelegation process within this constructor, improving clarity and ensuring that the MsgUndelegation instance is properly initialized.


77-93: LGTM!

The implementation of the validateDelegationInfo function performs comprehensive checks on the asset ID and the operator addresses, enforcing stricter validation and replacing the previous inline validation logic. This streamlines the validation process and improves the overall robustness of the delegation and undelegation processes.

x/delegation/keeper/abci.go (3)

41-41: Refactor: Consolidate types under a single namespace.

The change renames the imported delegationtype to types and uses types.GetUndelegationRecordKey instead of delegationtype.GetUndelegationRecordKey. This consolidates types under a single namespace without introducing any functional changes.


62-64: Refactor: Consolidate types under a single namespace.

The change updates the handling of the deltaAmount structure to use types.DeltaDelegationAmounts instead of delegationtype.DeltaDelegationAmounts. This is consistent with the overall renaming and suggests a consolidation of types under a single namespace without introducing any functional changes.


89-89: Refactor: Ensure consistency across asset state updates.

The change updates the error handling for updating the operator state to utilize assetstypes.DeltaOperatorSingleAsset, ensuring consistency across the asset state updates.

x/delegation/keeper/msg_server.go (3)

17-49: Enhance asset delegation logic and control flow.

The DelegateAssetToOperator method has been redefined to include comprehensive logic for handling asset delegation. It checks if the asset being delegated is the native asset, logging errors and returning appropriate responses if it is not. The method retrieves the account nonce and computes a unique hash for the transaction, which is used in the delegation process. It utilizes the newDelegationParams helper function to construct a list of delegation parameters.

These changes significantly improve the logic and control flow of asset delegation within the Keeper, allowing for more robust handling of the delegation process. The use of the newDelegationParams helper function enhances code clarity and reusability.


51-78: Add UndelegateAssetFromOperator method for enhanced asset undelegation functionality.

A new method, UndelegateAssetFromOperator, has been added, mirroring the structure of the delegation method. It checks for the native asset, retrieves the nonce, and computes a unique hash before proceeding with the undelegation logic. It utilizes the newDelegationParams helper function to construct a list of undelegation parameters.

The addition of this method enhances the functionality for asset undelegation, following a similar structure to the delegation method. The use of the newDelegationParams helper function ensures consistency and reusability across both methods.


81-98: Introduce newDelegationParams helper function for improved code modularity and reusability.

A new helper function, newDelegationParams, has been added to construct a list of delegation parameters based on the provided base information and asset details. It consolidates the logic for creating delegation parameters, which is used in both the delegation and undelegation methods.

The introduction of this helper function enhances code modularity and reusability by consolidating the logic for creating delegation parameters. This approach improves code clarity and maintainability.

proto/exocore/delegation/v1/tx.proto (2)

54-54: Breaking change: Modify per_operator_amounts field in DelegationIncOrDecInfo message.

The per_operator_amounts field in the DelegationIncOrDecInfo message has been changed from a map<string, ValueField> to a repeated KeyValue. This change alters how amounts are represented and may affect how data is serialized and deserialized, suggesting a more structured approach to handling multiple operator amounts, possibly enhancing clarity and usability.

However, as indicated by the static analysis tool, this change breaks compatibility with the previous version of the protocol.

Please verify the impact of this change on existing clients and data, and ensure that any necessary migration steps are documented and communicated to users. Consider the following:

  • How will existing data be migrated to the new format?
  • Will existing clients need to be updated to handle the new format?
  • Are there any potential data loss or corruption risks during the migration process?
  • How will the change be communicated to users and developers?
Tools
GitHub Check: break-check

[failure] 54-54:
Field "2" on message "DelegationIncOrDecInfo" changed type from "exocore.delegation.v1.DelegationIncOrDecInfo.PerOperatorAmountsEntry" to "exocore.delegation.v1.KeyValue".


59-60: Breaking change: Introduce asset_id field in MsgDelegation message.

A new asset_id field has been introduced at position 1 in the MsgDelegation message. This change emphasizes the importance of the asset ID in delegation operations, potentially impacting how these messages are processed in the system.

However, as indicated by the static analysis tool, this change breaks compatibility with the previous version of the protocol due to the change in field order and type.

Please verify the impact of this change on existing clients and message processing, and ensure that any necessary updates are made to maintain compatibility. Consider the following:

  • Will existing clients need to be updated to include the asset_id field when constructing MsgDelegation messages?
  • How will the system handle MsgDelegation messages that do not include the asset_id field?
  • Are there any potential risks or unintended consequences of changing the field order and type?
  • How will the change be communicated to users and developers?
Tools
GitHub Check: break-check

[failure] 60-60:
Field "1" with name "asset_id" on message "MsgDelegation" changed option "json_name" from "baseInfo" to "assetId".


[failure] 60-60:
Field "1" on message "MsgDelegation" changed type from "message" to "string".


[failure] 60-60:
Field "1" on message "MsgDelegation" changed name from "base_info" to "asset_id".

x/assets/keeper/staker_asset.go (3)

7-8: LGTM!

The new imports are necessary for the added functionality.


32-37: LGTM!

The new logic to retrieve native asset information for the staker aligns with the PR objective and the error handling looks good.


Line range hint 92-125:

Comment on lines 72 to 85
if record.AssetID == assetstypes.NativeAssetID {
parsedStakerID := strings.Split(record.StakerID, "_")
stakerAddr := sdk.AccAddress(hexutil.MustDecode(parsedStakerID[0]))
if err := k.bankKeeper.UndelegateCoinsFromModuleToAccount(ctx, types.DelegatedPoolName, stakerAddr, sdk.NewCoins(sdk.NewCoin(assetstypes.NativeAssetDenom, record.ActualCompletedAmount))); err != nil {
panic(err)
}
} else {
err = k.assetsKeeper.UpdateStakerAssetState(ctx, record.StakerID, record.AssetID, assetstypes.DeltaStakerSingleAsset{
WithdrawableAmount: record.ActualCompletedAmount,
WaitUnbondingAmount: recordAmountNeg,
})
if err != nil {
panic(err)
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Enhance clarity and performance for native asset undelegation, but avoid using panic for error handling.

The change introduces a new control flow that handles the undelegation of native assets differently from other assets. If the asset ID matches assetstypes.NativeAssetID, the code now parses the staker ID and directly undelegates coins from the module to the account, bypassing the previous method of updating the staker asset state for native assets. This enhances clarity and potentially improves performance.

However, the use of panic for error handling in lines 76 and 84 could cause a chain halt, as indicated by the static analysis tool.

Replace the panic calls with proper error handling:

-   if err := k.bankKeeper.UndelegateCoinsFromModuleToAccount(ctx, types.DelegatedPoolName, stakerAddr, sdk.NewCoins(sdk.NewCoin(assetstypes.NativeAssetDenom, record.ActualCompletedAmount))); err != nil {
-       panic(err)
-   }
+   err := k.bankKeeper.UndelegateCoinsFromModuleToAccount(ctx, types.DelegatedPoolName, stakerAddr, sdk.NewCoins(sdk.NewCoin(assetstypes.NativeAssetDenom, record.ActualCompletedAmount)))
+   if err != nil {
+       return nil, err
+   }

-   if err != nil {
-       panic(err)
-   }
+   if err != nil {
+       return nil, err
+   }
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if record.AssetID == assetstypes.NativeAssetID {
parsedStakerID := strings.Split(record.StakerID, "_")
stakerAddr := sdk.AccAddress(hexutil.MustDecode(parsedStakerID[0]))
if err := k.bankKeeper.UndelegateCoinsFromModuleToAccount(ctx, types.DelegatedPoolName, stakerAddr, sdk.NewCoins(sdk.NewCoin(assetstypes.NativeAssetDenom, record.ActualCompletedAmount))); err != nil {
panic(err)
}
} else {
err = k.assetsKeeper.UpdateStakerAssetState(ctx, record.StakerID, record.AssetID, assetstypes.DeltaStakerSingleAsset{
WithdrawableAmount: record.ActualCompletedAmount,
WaitUnbondingAmount: recordAmountNeg,
})
if err != nil {
panic(err)
}
if record.AssetID == assetstypes.NativeAssetID {
parsedStakerID := strings.Split(record.StakerID, "_")
stakerAddr := sdk.AccAddress(hexutil.MustDecode(parsedStakerID[0]))
err := k.bankKeeper.UndelegateCoinsFromModuleToAccount(ctx, types.DelegatedPoolName, stakerAddr, sdk.NewCoins(sdk.NewCoin(assetstypes.NativeAssetDenom, record.ActualCompletedAmount)))
if err != nil {
return nil, err
}
} else {
err = k.assetsKeeper.UpdateStakerAssetState(ctx, record.StakerID, record.AssetID, assetstypes.DeltaStakerSingleAsset{
WithdrawableAmount: record.ActualCompletedAmount,
WaitUnbondingAmount: recordAmountNeg,
})
if err != nil {
return nil, err
}
}
Tools
GitHub Check: CodeQL

[warning] 76-76: Panic in BeginBock or EndBlock consensus methods
Possible panics in BeginBock- or EndBlock-related consensus methods could cause a chain halt


[warning] 76-76: Panic in BeginBock or EndBlock consensus methods
path flow from Begin/EndBlock to a panic call


[warning] 84-84: Panic in BeginBock or EndBlock consensus methods
Possible panics in BeginBock- or EndBlock-related consensus methods could cause a chain halt


[warning] 84-84: Panic in BeginBock or EndBlock consensus methods
path flow from Begin/EndBlock to a panic call

@MaxMustermann2
Copy link
Contributor

With this PR native aexo token (not native restaking of ETH) will be in the system. Since this token isn't on Chainlink, it is unlikely that the x/oracle module will be able to feed a price for it. We will need to hardcode a price (for testnet and mainnet) until a supported source is available.

@leonz789 leonz789 added the enhancement New feature or request label Sep 15, 2024
@cloud8little
Copy link
Contributor

@leonz789 good to merge.

@leonz789 leonz789 force-pushed the develop-delegation-nativetoken branch from f34bb2c to 651715a Compare September 21, 2024 00:42
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 14

Outside diff range and nitpick comments (7)
x/delegation/types/general.go (1)

5-10: LGTM! The new constants improve code clarity and maintainability.

The introduction of the NotBondedPoolName, BondedPoolName, and DelegatedPoolName constants in the types package is a great addition. It provides a centralized and standardized way to refer to the different token pools across the delegation module, reducing the risk of inconsistencies and making the code more maintainable.

The constant names are clear, descriptive, and follow the naming convention of appending "PoolName" to each constant, which enhances code readability.

The TODO comment provides valuable context for the use of DelegatedPoolName, indicating that it's a temporary solution until redelegation and operator bonding are fully implemented. This comment serves as a reminder for future enhancements and ensures that the current limitations are clearly communicated to other developers.

To address the TODO comment, consider creating a new GitHub issue to track the implementation of redelegation and operator bonding. This will ensure that the task is properly prioritized and not overlooked in the future. Let me know if you'd like me to assist in creating the issue.

x/delegation/client/cli/tx_delegation_native.go (1)

43-43: Address the limitation mentioned in the TODO comment.

Similar to the CmdDelegate function, the TODO comment indicates that the command currently only supports native tokens. Consider expanding the support to other token types in future iterations to enhance the functionality of the command.

x/delegation/keeper/share.go (1)

226-227: Address the TODO comment.

The comment suggests potential issues with precision loss or other inaccuracies in the calculation of TotalDepositAmount. It's important to investigate and address this concern to ensure accurate financial calculations.

Do you want me to open a GitHub issue to track this task?

x/delegation/keeper/keeper.go (2)

67-69: Add Comment for Exported Method Logger

The method Logger is exported but lacks a comment. It's best practice in Go to document exported methods to enhance code readability and maintainability.

Apply this diff to add a comment:

+// Logger returns a module-specific logger.
func (k Keeper) Logger(ctx sdk.Context) log.Logger {
    return ctx.Logger().With("module", fmt.Sprintf("x/%s", delegationtype.ModuleName))
}

67-69: Consider Using Pointer Receiver for Consistency

The Logger method uses a value receiver (k Keeper), whereas other methods like SetHooks use a pointer receiver (k *Keeper). For consistency across the codebase, consider using a pointer receiver for the Logger method.

Apply this diff to change the receiver type:

-func (k Keeper) Logger(ctx sdk.Context) log.Logger {
+func (k *Keeper) Logger(ctx sdk.Context) log.Logger {
    return ctx.Logger().With("module", fmt.Sprintf("x/%s", delegationtype.ModuleName))
}
x/delegation/types/msg.go (1)

76-76: Consider unifying MsgDelegation and MsgUndelegation

Since both messages share the same parameters, consolidating them into a single message with an action flag (e.g., IsDelegation bool) could reduce redundancy and simplify the API.

x/delegation/keeper/delegation_op_test.go (1)

Line range hint 312-451: Extract epoch advancement logic into a helper function

The loops advancing epochs are repeated for both asset types in TestCompleteUndelegation. Refactoring this logic into a helper function will reduce code duplication and improve readability.

Apply this refactor:

+func (suite *DelegationTestSuite) advanceEpochs(epochsUntilUnbonded int64) {
+	epochID := suite.App.StakingKeeper.GetEpochIdentifier(suite.Ctx)
+	epochInfo, _ := suite.App.EpochsKeeper.GetEpochInfo(suite.Ctx, epochID)
+	for i := 0; i < int(epochsUntilUnbonded); i++ {
+		epochEndTime := epochInfo.CurrentEpochStartTime.Add(epochInfo.Duration)
+		suite.Ctx = suite.Ctx.WithBlockTime(epochEndTime.Add(1 * time.Second))
+		suite.App.EpochsKeeper.BeginBlocker(suite.Ctx)
+		epochInfo, _ = suite.App.EpochsKeeper.GetEpochInfo(suite.Ctx, epochID)
+	}
+}

 func (suite *DelegationTestSuite) TestCompleteUndelegation() {
 	// existing code...
-	for i := 0; i < int(epochsUntilUnbonded); i++ {
-		epochEndTime := epochInfo.CurrentEpochStartTime.Add(epochInfo.Duration)
-		suite.Ctx = suite.Ctx.WithBlockTime(epochEndTime.Add(1 * time.Second))
-		suite.App.EpochsKeeper.BeginBlocker(suite.Ctx)
-		epochInfo, _ = suite.App.EpochsKeeper.GetEpochInfo(suite.Ctx, epochID)
-	}
+	suite.advanceEpochs(epochsUntilUnbonded)

 	// existing code...

-	for i := 0; i < int(epochsUntilUnbonded); i++ {
-		epochEndTime := epochInfo.CurrentEpochStartTime.Add(epochInfo.Duration)
-		suite.Ctx = suite.Ctx.WithBlockTime(epochEndTime.Add(1 * time.Second))
-		suite.App.EpochsKeeper.BeginBlocker(suite.Ctx)
-		epochInfo, _ = suite.App.EpochsKeeper.GetEpochInfo(suite.Ctx, epochID)
-	}
+	suite.advanceEpochs(epochsUntilUnbonded)
 }
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between f34bb2c and 651715a.

Files ignored due to path filters (1)
  • x/delegation/types/tx.pb.go is excluded by !**/*.pb.go
Files selected for processing (29)
  • app/app.go (9 hunks)
  • proto/exocore/delegation/v1/tx.proto (2 hunks)
  • testutil/utils.go (0 hunks)
  • x/assets/client/cli/tx.go (0 hunks)
  • x/assets/keeper/bank.go (1 hunks)
  • x/assets/keeper/expected_keepers.go (1 hunks)
  • x/assets/keeper/keeper.go (1 hunks)
  • x/assets/keeper/staker_asset.go (2 hunks)
  • x/assets/keeper/staker_asset_test.go (1 hunks)
  • x/assets/types/expected_keepers.go (1 hunks)
  • x/assets/types/general.go (1 hunks)
  • x/delegation/client/cli/tx.go (1 hunks)
  • x/delegation/client/cli/tx_delegation_native.go (1 hunks)
  • x/delegation/keeper/abci.go (4 hunks)
  • x/delegation/keeper/delegation.go (1 hunks)
  • x/delegation/keeper/delegation_op_test.go (7 hunks)
  • x/delegation/keeper/delegation_state.go (1 hunks)
  • x/delegation/keeper/keeper.go (4 hunks)
  • x/delegation/keeper/msg_server.go (1 hunks)
  • x/delegation/keeper/setup_test.go (2 hunks)
  • x/delegation/keeper/share.go (1 hunks)
  • x/delegation/types/cross_chain_params.go (1 hunks)
  • x/delegation/types/errors.go (1 hunks)
  • x/delegation/types/expected_keepers.go (1 hunks)
  • x/delegation/types/general.go (1 hunks)
  • x/delegation/types/msg.go (3 hunks)
  • x/oracle/keeper/prices.go (3 hunks)
  • x/reward/keeper/claim_reward.go (1 hunks)
  • x/slash/keeper/execute_slash.go (6 hunks)
Files not reviewed due to no reviewable changes (2)
  • testutil/utils.go
  • x/assets/client/cli/tx.go
Additional context used
GitHub Check: break-check
proto/exocore/delegation/v1/tx.proto

[failure] 54-54:
Field "2" on message "DelegationIncOrDecInfo" changed type from "exocore.delegation.v1.DelegationIncOrDecInfo.PerOperatorAmountsEntry" to "exocore.delegation.v1.KeyValue".


[failure] 60-60:
Field "1" with name "asset_id" on message "MsgDelegation" changed option "json_name" from "baseInfo" to "assetId".


[failure] 60-60:
Field "1" on message "MsgDelegation" changed type from "message" to "string".


[failure] 60-60:
Field "1" on message "MsgDelegation" changed name from "base_info" to "asset_id".


[failure] 62-62:
Field "2" with name "base_info" on message "MsgDelegation" changed option "json_name" from "approvedInfo" to "baseInfo".


[failure] 62-62:
Field "2" on message "MsgDelegation" changed type from "exocore.delegation.v1.DelegationApproveInfo" to "exocore.delegation.v1.DelegationIncOrDecInfo".


[failure] 62-62:
Field "2" on message "MsgDelegation" changed name from "approved_info" to "base_info".


[failure] 113-113:
Field "1" with name "asset_id" on message "MsgUndelegation" changed option "json_name" from "baseInfo" to "assetId".

Additional comments not posted (49)
x/assets/keeper/expected_keepers.go (1)

1-11: The past review comments discussing the placement of the delegationKeeper interface definition and the reasoning behind it are still valid. The comment explaining the reason for placing the interface definition in the keeper package to avoid a circular dependency has been added as suggested. No further action is required.

x/assets/types/expected_keepers.go (1)

12-15: LGTM!

The addition of the BankKeeper interface aligns with the PR objective of managing native token asset information through the bank module. The GetBalance method will enable querying account balances for delegation and undelegation operations within the assets module.

x/delegation/client/cli/tx.go (1)

21-23: LGTM!

The addition of the CmdDelegate() and CmdUndelegate() commands to the txCmd command set is a valuable enhancement that aligns with the PR objectives. The function names are consistent with the intended functionality, and the changes are well-integrated into the existing command structure.

x/delegation/keeper/setup_test.go (2)

8-8: LGTM!

The import statement for the sdk package from github.com/cosmos/cosmos-sdk/types is valid and follows the correct syntax. It is a commonly used Cosmos SDK package for handling types and is likely added to support the usage of sdk.AccAddress type in the test suite.


23-23: LGTM!

The addition of the accAddr field of type sdk.AccAddress to the DelegationTestSuite struct is valid and follows the correct syntax. The sdk.AccAddress type is a commonly used Cosmos SDK type for representing account addresses. The field is likely added to store an account address that will be used in the test cases.

x/delegation/types/cross_chain_params.go (1)

22-42: LGTM!

The addition of the NewDelegationOrUndelegationParams constructor function is a good practice. It enhances the usability of the DelegationOrUndelegationParams struct by providing a clear method for instantiation and ensures that all fields are properly initialized when creating a new instance of the struct.

The function takes the necessary parameters and initializes the struct fields correctly. The logic and syntax are accurate.

x/assets/keeper/bank.go (1)

43-56: Address the TODO comment to ensure correct handling of the native token.

The past review comment is still valid and applicable:

The addition of a condition to skip updating staker info for exo-native-token is a significant change. This logic ensures that operations specific to the native token are handled differently, which is crucial given its unique role in the ecosystem.

However, the TODO comment indicates uncertainty about whether additional processes are needed for exo-native-token. It's important to address this to ensure that all necessary operations for the native token are correctly implemented.

Please ensure that you have thoroughly considered and implemented all necessary operations for the native token. Skipping updates for the native token without proper handling could lead to inconsistencies in the asset state and total amount.

To verify the correct handling of the native token, run the following script:

#!/bin/bash
# Description: Verify that all necessary operations for the native token are implemented correctly.

# Test 1: Search for any additional processes specific to the native token.
rg --type go -A 5 $'assetstypes\.NativeAssetID'

# Test 2: Search for any inconsistencies in the asset state and total amount for the native token.
ast-grep --lang go --pattern $'if $$$; err != nil {
  return errorsmod.Wrapf(err, $$$)
}'

If the script output reveals any missing operations or inconsistencies, please address them to ensure the correct handling of the native token.

x/delegation/types/errors.go (1)

82-85: LGTM!

The new error variable ErrInvalidAssetID is declared and registered correctly, following the existing pattern in the file. The error code 18 is unique and follows the sequence of the existing error codes. The error message clearly conveys the purpose of the error, indicating that the asset ID is invalid.

This addition will help in identifying and handling cases where an invalid asset ID is encountered in the delegation module, improving error handling and providing a specific error message for such scenarios.

x/delegation/client/cli/tx_delegation_native.go (2)

18-18: ****
Address the limitation mentioned in the TODO comment.

The TODO comment indicates that the command currently only supports native tokens. Consider expanding the support to other token types in future iterations to enhance the functionality of the command.


68-82: ****
Improve the input validation in parseArgs.

Please apply the following changes suggested in the previous review comment:

-  if len(args) != 3 {
-    return "", "", sdkmath.ZeroInt(), errors.New("3 arguments needed")
-  }
+  if len(args) != 3 {
+    return "", "", sdkmath.ZeroInt(), errors.New("exactly 3 arguments are required")
+  }

   assetID := args[0]
   operatorAddrStr := args[1]

   amount, ok := sdkmath.NewIntFromString(args[2])
   if !ok || amount.LTE(sdkmath.ZeroInt()) {
     return "", "", sdkmath.ZeroInt(), errors.New("amount invalid")
   }

   return assetID, operatorAddrStr, amount, nil
x/assets/keeper/keeper.go (2)

16-17: LGTM!

The addition of the bk and dk fields to the Keeper struct is a necessary step to enable the assets module to interact with the bank and delegation modules. This change aligns with the PR objective of integrating delegation functionality for native tokens.


24-25: Looks good!

The updates to the NewKeeper constructor are necessary to initialize the newly added bk and dk fields in the Keeper struct. These changes maintain consistency with the struct modifications and ensure that the assets module has access to the required dependencies from the bank and delegation modules.

Also applies to: 31-32

x/delegation/types/expected_keepers.go (2)

57-61: LGTM!

The BankKeeper interface provides a clean abstraction for managing coin balances and delegation/undelegation flows between accounts and modules. The method signatures are well-defined and serve their intended purpose.


63-65: LGTM!

The AccountKeeper interface provides a clear abstraction for account-related operations. The GetSequence method is essential for retrieving the account sequence number, which plays a vital role in transaction ordering and preventing replay attacks.

x/delegation/keeper/msg_server.go (3)

17-49: LGTM!

The DelegateAssetToOperator function implements the core logic for delegating assets to an operator. Here are the key aspects of the function:

  • It checks if the asset being delegated is the native asset and returns an error if not. This ensures that only supported assets are delegated.
  • It retrieves the nonce for the sender's address and computes a unique hash based on the transaction bytes and nonce. This helps in generating a unique identifier for each delegation transaction.
  • It creates delegation parameters using the newDelegationParams helper function, which makes the code more modular and reusable.
  • It attempts to delegate the asset using the generated delegation parameters and logs any errors encountered during the process.

The function is well-structured and follows good practices such as error handling and logging.


51-78: LGTM!

The UndelegateAssetFromOperator function implements the core logic for undelegating assets from an operator. Here are the key aspects of the function:

  • It checks if the asset being undelegated is the native asset and returns an error if not. This ensures that only supported assets are undelegated.
  • It retrieves the nonce for the sender's address and computes a unique hash based on the transaction bytes and nonce. This helps in generating a unique identifier for each undelegation transaction.
  • It creates undelegation parameters using the newDelegationParams helper function, which is reused from the delegation logic. This promotes code reusability and maintainability.
  • It attempts to undelegate the asset using the generated undelegation parameters and returns any error encountered during the process.

The function follows a similar structure to the DelegateAssetToOperator function and adheres to good practices such as error handling and code reuse.


81-98: LGTM!

The newDelegationParams function is a helper function that generates a list of delegation or undelegation parameters based on the provided base information and other necessary details. Here are the key aspects of the function:

  • It takes the base info, asset address, client chain ID, nonce, and transaction hash as parameters.
  • It creates a slice of DelegationOrUndelegationParams with a capacity of 1 to store the generated parameters.
  • It iterates over the PerOperatorAmounts map in the base information and creates a DelegationOrUndelegationParams object for each entry using the NewDelegationOrUndelegationParams function.
  • It appends each DelegationOrUndelegationParams object to the result slice and returns the slice.

The function encapsulates the logic for creating DelegationOrUndelegationParams objects, making the code more modular and reusable. It is used by both the DelegateAssetToOperator and UndelegateAssetFromOperator functions, promoting code reuse and maintainability.

x/assets/types/general.go (1)

16-21: LGTM!

The new constant block is well-defined and provides a clear, centralized definition for the native asset and chain properties. The use of utils.BaseDenom for NativeAssetDenom aligns with the suggestion from the previous review comment.

proto/exocore/delegation/v1/tx.proto (5)

54-54: Approve the change from map to repeated KeyValue for per_operator_amounts.

The change from using a map to a repeated KeyValue type for the per_operator_amounts field is a good solution to ensure a consistent order of the data. As mentioned in the comment, the order of insertion in a map affects the state root in Cosmos, and deserializing a protobuf map into Golang does not guarantee order. Using a repeated field of key-value pairs instead of a map mitigates this issue.

Setting gogoproto.nullable to false for this field is also a good practice to ensure that it cannot be left unset.

Note that this change will require corresponding updates in the code that uses this message to handle the new structure.

Tools
GitHub Check: break-check

[failure] 54-54:
Field "2" on message "DelegationIncOrDecInfo" changed type from "exocore.delegation.v1.DelegationIncOrDecInfo.PerOperatorAmountsEntry" to "exocore.delegation.v1.KeyValue".


59-60: Approve the addition of the asset_id field to MsgDelegation.

Adding the asset_id field to the MsgDelegation message at position 1 is a good change that allows specifying the identity of the asset being delegated. Using the gogoproto.customname option with "AssetID" ensures that the field follows the Go naming convention in the generated code.

Please note that this is a breaking change for the MsgDelegation message, as it adds a new required field. Any code that creates or handles MsgDelegation messages will need to be updated to provide the asset_id.

Tools
GitHub Check: break-check

[failure] 60-60:
Field "1" with name "asset_id" on message "MsgDelegation" changed option "json_name" from "baseInfo" to "assetId".


[failure] 60-60:
Field "1" on message "MsgDelegation" changed type from "message" to "string".


[failure] 60-60:
Field "1" on message "MsgDelegation" changed name from "base_info" to "asset_id".


62-62: Approve the change in the field order for MsgDelegation.

Moving the base_info field to position 2 in the MsgDelegation message is a necessary change to maintain the correct field order after adding the new asset_id field at position 1.

Please note that this is a breaking change for the MsgDelegation message. Any code that creates or handles MsgDelegation messages will need to be updated to use the new field order.

Tools
GitHub Check: break-check

[failure] 62-62:
Field "2" with name "base_info" on message "MsgDelegation" changed option "json_name" from "approvedInfo" to "baseInfo".


[failure] 62-62:
Field "2" on message "MsgDelegation" changed type from "exocore.delegation.v1.DelegationApproveInfo" to "exocore.delegation.v1.DelegationIncOrDecInfo".


[failure] 62-62:
Field "2" on message "MsgDelegation" changed name from "approved_info" to "base_info".


112-113: Approve the addition of the asset_id field to MsgUndelegation.

Adding the asset_id field to the MsgUndelegation message at position 1 is a good change that allows specifying the identity of the asset being undelegated. Using the gogoproto.customname option with "AssetID" ensures that the field follows the Go naming convention in the generated code.

Please note that this is a breaking change for the MsgUndelegation message, as it adds a new required field. Any code that creates or handles MsgUndelegation messages will need to be updated to provide the asset_id.

Tools
GitHub Check: break-check

[failure] 113-113:
Field "1" with name "asset_id" on message "MsgUndelegation" changed option "json_name" from "baseInfo" to "assetId".


115-115: Approve the change in the field order for MsgUndelegation.

Moving the base_info field to position 2 in the MsgUndelegation message is a necessary change to maintain the correct field order after adding the new asset_id field at position 1.

Please note that this is a breaking change for the MsgUndelegation message. Any code that creates or handles MsgUndelegation messages will need to be updated to use the new field order.

x/assets/keeper/staker_asset_test.go (1)

84-84: LGTM!

The change to the stakerID format is a minor update that doesn't affect the correctness of the test. It might be for consistency with how stakerID is represented in other parts of the codebase.

x/slash/keeper/execute_slash.go (4)

27-27: LGTM!

The Action field type update aligns with the import alias change.


Line range hint 47-105: LGTM!

The updates to variable types and references in the getParamsFromEventLog function align with the import alias change from types to assetstypes. The changes are consistent and do not introduce any apparent issues.


194-195: Clarify the comment about additional processes for native tokens.

The comment on line 195 asks whether additional processes are needed for native tokens. This requires clarification to ensure that the special handling of native tokens is properly implemented and does not introduce any unintended consequences.


196-208: Verify the impact of skipping asset state updates for native tokens.

The conditional block for updating staker asset state and staking asset total amount has been updated to skip these updates for native tokens. It's crucial to ensure that this change does not lead to inconsistencies in the system's state management.

Please verify that skipping these updates for native tokens is the intended behavior and does not introduce any issues or discrepancies in the overall asset management logic.

x/oracle/keeper/prices.go (2)

50-57: LGTM!

The added conditional check correctly handles the special case for the native asset identified by assetstypes.NativeAssetID. Returning a default price for the native asset using predefined constants is a necessary and maintainable approach.


103-110: Looks good!

The added conditional check correctly handles the special case for the native asset identified by assetstypes.NativeAssetID within the loop. Assigning a default price to the prices map for the native asset and using the continue statement to move to the next asset is a clean and maintainable approach.

x/delegation/keeper/delegation_state.go (1)

197-197: Improved error handling using a custom error type.

The change from using errorsmod.Wrap to delegationtype.ErrNoKeyInTheStore.Wrapf enhances the error handling in the GetSingleDelegationInfo method. By utilizing a custom error type specific to the delegation package, the code provides more context about the error scenario. The Wrapf method also allows for formatting the error message with additional details, making it more informative.

This change improves the overall error handling without introducing any new bugs or logic errors. The modification is localized and does not affect other parts of the codebase.

x/delegation/keeper/keeper.go (2)

19-23: New Keeper Dependencies Added Correctly

The accountKeeper and bankKeeper have been appropriately added to the Keeper struct. This integration aligns with the requirements for managing native token delegation and undelegation.


33-34: Verify Initialization of New Keeper Dependencies

The NewKeeper constructor now includes accountKeeper and bankKeeper. Ensure that all instances where NewKeeper is called are updated to pass these new dependencies to prevent potential runtime errors.

Run the following script to find all usages of NewKeeper and check if they include the new parameters:

Also applies to: 42-43

Verification successful

To gather the necessary information for a conclusive verification, we need to examine the NewKeeper function in the delegation module and its usage in app/app.go more closely. Let's run the following scripts:


To complete our verification, we need to extend the search context for the DelegationKeeper initialization in app/app.go. Let's run the following script:


Verification Successful: NewKeeper Dependencies Properly Updated

The NewKeeper constructor in the delegation module has been correctly updated to include accountKeeper and bankKeeper. The initialization of DelegationKeeper in app/app.go has also been properly updated to pass these new dependencies. No further changes are required.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all calls to NewKeeper and display them with context.

# Test: Search for NewKeeper function calls.
# Expect: All calls include accountKeeper and bankKeeper as arguments.
rg --type go -A 3 -B 3 'NewKeeper\('

Length of output: 13845


Script:

#!/bin/bash
# Description: Examine the NewKeeper function in the delegation module and its usage in app/app.go

# Check the NewKeeper function in the delegation module
echo "Delegation Module NewKeeper:"
rg --type go -A 10 'func NewKeeper\(' x/delegation/keeper/keeper.go

# Check the initialization of DelegationKeeper in app/app.go
echo "\nDelegationKeeper Initialization in app/app.go:"
rg --type go -A 5 'app.DelegationKeeper =' app/app.go

Length of output: 840


Script:

#!/bin/bash
# Description: Examine the DelegationKeeper initialization in app/app.go with extended context

echo "DelegationKeeper Initialization in app/app.go (extended context):"
rg --type go -A 10 'app.DelegationKeeper =' app/app.go

Length of output: 587

x/delegation/types/msg.go (2)

22-23: Good use of centralized validation with validateDelegationInfo

By centralizing the validation logic in validateDelegationInfo, you enhance code reusability and maintainability.


53-53: Consistent use of centralized validation in MsgUndelegation

Reusing validateDelegationInfo in MsgUndelegation promotes consistency and reduces code duplication.

x/assets/keeper/staker_asset.go (1)

102-113: Non-deterministic iteration over maps

Iterating over maps in Go does not guarantee order, which can cause non-deterministic behavior in blockchain applications. This issue has been previously identified and is still applicable.

x/delegation/keeper/delegation.go (4)

41-46: Correct handling of non-native assets

The code correctly checks for non-native assets and retrieves the staker's specified asset information with proper error handling.


48-50: Proper validation of withdrawable amount

The validation ensures that the staker has sufficient withdrawable amount before proceeding with the delegation, which is implemented correctly.


52-58: Staker asset state updated appropriately

The staker's asset state is updated by decreasing the withdrawable amount by the operation amount, and the error handling is properly managed.


59-64: Correct delegation of native assets

The code appropriately handles the delegation of native assets by constructing the coin and transferring it from the staker's account to the delegated pool with proper error handling.

x/delegation/keeper/delegation_op_test.go (1)

28-28: Verify the initialization of suite.accAddr

At line 28, suite.accAddr is initialized using sdk.AccAddress(suite.Address.Bytes()). Please ensure that suite.Address is properly initialized before this assignment to prevent potential issues with an uninitialized or incorrect address.

app/app.go (7)

119-120: Integration of vesting module imports is appropriate

The addition of the vesting module imports is correct for incorporating vesting functionalities.


253-253: Include vesting module in ModuleBasics

Adding vesting.AppModuleBasic{} ensures the vesting module is properly registered in ModuleBasics.


284-286: Verify module account permissions for delegation module

The delegationTypes.DelegatedPoolName is assigned both authtypes.Burner and authtypes.Staking permissions. Please confirm that granting the authtypes.Staking permission is necessary and does not pose security risks.


541-541: Ensure correct initialization of AssetsKeeper with DelegationKeeper

The AssetsKeeper now includes a reference to &app.DelegationKeeper. Verify that this addition is required and that there are no circular dependency issues introduced.


549-550: Addition of AccountKeeper and BankKeeper to DelegationKeeper

Including app.AccountKeeper and app.BankKeeper in the DelegationKeeper initialization ensures proper handling of accounts and balances within the delegation module.


811-811: Add vesting module to the module manager

Including vesting.NewAppModule(app.AccountKeeper, app.BankKeeper) integrates the vesting module into the application's module manager appropriately.


900-900: Confirm vesting module's placement in module execution order

The vestingtypes.ModuleName is added to SetOrderBeginBlockers, SetOrderEndBlockers, and SetOrderInitGenesis. Please verify that its placement aligns with its dependencies and initialization requirements to prevent any unintended execution issues.

Also applies to: 935-935, 980-980

x/reward/keeper/claim_reward.go (1)

143-151: Previous comment is still valid

Comment on lines +224 to +233
// don't update staker asset info for exo-native-token
if assetID != assetstype.NativeAssetID {
// todo: TotalDepositAmount might be influenced by slash and precision loss,
// consider removing it, it can be recalculated from the share for RPC query.
err = k.assetsKeeper.UpdateStakerAssetState(ctx, stakerID, assetID, assetstype.DeltaStakerSingleAsset{
PendingUndelegationAmount: removeToken,
})
if err != nil {
return removeToken, err
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tip

Codebase Verification

Inconsistent handling of native asset detected

The conditional check for assetstype.NativeAssetID before calling UpdateStakerAssetState is not consistently applied across the codebase. While it's present in the reviewed file (x/delegation/keeper/share.go) and x/delegation/keeper/delegation.go, other occurrences of UpdateStakerAssetState lack this check.

This inconsistency may lead to unexpected behavior in parts of the system that don't have this check. To ensure consistent handling of the native asset:

  • Review all occurrences of UpdateStakerAssetState in the codebase.
  • Evaluate whether the conditional check for assetstype.NativeAssetID should be applied universally or if there are valid reasons for its absence in some cases.
  • Update the relevant functions to maintain consistency in native asset handling.
Analysis chain

Conditional check for exo-native token looks good!

The introduction of the conditional check to skip updating staker asset state for the exo-native token is a critical change for handling these assets. It alters the control flow and affects whether the UpdateStakerAssetState method is called.

To ensure consistency, please run the following script to verify that skipping the update of staker asset state for the exo-native token aligns with other parts of the system:

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify consistency of skipping staker asset state update for exo-native token.

# Test 1: Search for other occurrences of `assetstype.NativeAssetID` and analyze the associated logic.
rg --type go -A 5 $'assetstype.NativeAssetID'

# Test 2: Search for `UpdateStakerAssetState` calls and check if they have similar conditional checks.
rg --type go -A 5 $'UpdateStakerAssetState'

Length of output: 13915

Comment on lines +61 to +74
// new message to delegate asset to operator
func NewMsgUndelegation(assetID, fromAddress string, amountPerOperator []KeyValue) *MsgUndelegation {
baseInfo := &DelegationIncOrDecInfo{
FromAddress: fromAddress,
PerOperatorAmounts: make([]KeyValue, 0, 1),
}
for _, kv := range amountPerOperator {
baseInfo.PerOperatorAmounts = append(baseInfo.PerOperatorAmounts, KeyValue{Key: kv.Key, Value: kv.Value})
}
return &MsgUndelegation{
AssetID: assetID,
BaseInfo: baseInfo,
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optimize slice allocation in NewMsgUndelegation

Similar to NewMsgDelegation, adjust the slice capacity of PerOperatorAmounts to the length of amountPerOperator for better performance.

Apply this diff to adjust the slice capacity:

-		PerOperatorAmounts: make([]KeyValue, 0, 1),
+		PerOperatorAmounts: make([]KeyValue, 0, len(amountPerOperator)),
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// new message to delegate asset to operator
func NewMsgUndelegation(assetID, fromAddress string, amountPerOperator []KeyValue) *MsgUndelegation {
baseInfo := &DelegationIncOrDecInfo{
FromAddress: fromAddress,
PerOperatorAmounts: make([]KeyValue, 0, 1),
}
for _, kv := range amountPerOperator {
baseInfo.PerOperatorAmounts = append(baseInfo.PerOperatorAmounts, KeyValue{Key: kv.Key, Value: kv.Value})
}
return &MsgUndelegation{
AssetID: assetID,
BaseInfo: baseInfo,
}
}
// new message to delegate asset to operator
func NewMsgUndelegation(assetID, fromAddress string, amountPerOperator []KeyValue) *MsgUndelegation {
baseInfo := &DelegationIncOrDecInfo{
FromAddress: fromAddress,
PerOperatorAmounts: make([]KeyValue, 0, len(amountPerOperator)),
}
for _, kv := range amountPerOperator {
baseInfo.PerOperatorAmounts = append(baseInfo.PerOperatorAmounts, KeyValue{Key: kv.Key, Value: kv.Value})
}
return &MsgUndelegation{
AssetID: assetID,
BaseInfo: baseInfo,
}
}

Comment on lines +77 to +93
func validateDelegationInfo(assetID string, baseInfo *DelegationIncOrDecInfo) error {
for _, kv := range baseInfo.PerOperatorAmounts {
if _, err := sdk.AccAddressFromBech32(kv.Key); err != nil {
return errorsmod.Wrap(err, "invalid operator address delegateTO")
}
if !kv.Value.Amount.IsPositive() {
return errorsmod.Wrapf(ErrAmountIsNotPositive, "amount should be positive, got%s", kv.Value.Amount.String())
}
}
if assetID != assetstype.NativeAssetID {
return errorsmod.Wrapf(ErrInvalidAssetID, "only nativeToken is support, expected:%s,got:%s", assetstype.NativeAssetID, assetID)
}
if _, err := sdk.AccAddressFromBech32(baseInfo.FromAddress); err != nil {
return errorsmod.Wrap(err, "invalid from address")
}
return nil
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct typos and improve error messages in validateDelegationInfo

Several error messages contain typos or grammatical errors that could be clarified.

Apply the following diffs to correct the error messages:

-			return errorsmod.Wrap(err, "invalid operator address delegateTO")
+			return errorsmod.Wrap(err, "invalid operator address to delegate to")

-			return errorsmod.Wrapf(ErrAmountIsNotPositive, "amount should be positive, got%s", kv.Value.Amount.String())
+			return errorsmod.Wrapf(ErrAmountIsNotPositive, "amount should be positive, got %s", kv.Value.Amount.String())

-		return errorsmod.Wrapf(ErrInvalidAssetID, "only nativeToken is support, expected:%s,got:%s", assetstype.NativeAssetID, assetID)
+		return errorsmod.Wrapf(ErrInvalidAssetID, "only native token is supported; expected: %s, got: %s", assetstype.NativeAssetID, assetID)
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func validateDelegationInfo(assetID string, baseInfo *DelegationIncOrDecInfo) error {
for _, kv := range baseInfo.PerOperatorAmounts {
if _, err := sdk.AccAddressFromBech32(kv.Key); err != nil {
return errorsmod.Wrap(err, "invalid operator address delegateTO")
}
if !kv.Value.Amount.IsPositive() {
return errorsmod.Wrapf(ErrAmountIsNotPositive, "amount should be positive, got%s", kv.Value.Amount.String())
}
}
if assetID != assetstype.NativeAssetID {
return errorsmod.Wrapf(ErrInvalidAssetID, "only nativeToken is support, expected:%s,got:%s", assetstype.NativeAssetID, assetID)
}
if _, err := sdk.AccAddressFromBech32(baseInfo.FromAddress); err != nil {
return errorsmod.Wrap(err, "invalid from address")
}
return nil
}
func validateDelegationInfo(assetID string, baseInfo *DelegationIncOrDecInfo) error {
for _, kv := range baseInfo.PerOperatorAmounts {
if _, err := sdk.AccAddressFromBech32(kv.Key); err != nil {
return errorsmod.Wrap(err, "invalid operator address to delegate to")
}
if !kv.Value.Amount.IsPositive() {
return errorsmod.Wrapf(ErrAmountIsNotPositive, "amount should be positive, got %s", kv.Value.Amount.String())
}
}
if assetID != assetstype.NativeAssetID {
return errorsmod.Wrapf(ErrInvalidAssetID, "only native token is supported; expected: %s, got: %s", assetstype.NativeAssetID, assetID)
}
if _, err := sdk.AccAddressFromBech32(baseInfo.FromAddress); err != nil {
return errorsmod.Wrap(err, "invalid from address")
}
return nil
}

Comment on lines +25 to +36
// new message to delegate asset to operator
func NewMsgDelegation(assetID, fromAddress string, amountPerOperator []KeyValue) *MsgDelegation {
baseInfo := &DelegationIncOrDecInfo{
FromAddress: fromAddress,
PerOperatorAmounts: make([]KeyValue, 0, 1),
}
for _, kv := range amountPerOperator {
baseInfo.PerOperatorAmounts = append(baseInfo.PerOperatorAmounts, KeyValue{Key: kv.Key, Value: kv.Value})
}
return &MsgDelegation{
AssetID: assetID,
BaseInfo: baseInfo,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optimize slice allocation in NewMsgDelegation

When initializing PerOperatorAmounts, consider setting the slice capacity to match the length of amountPerOperator to improve efficiency and avoid unnecessary allocations.

Apply this diff to adjust the slice capacity:

-		PerOperatorAmounts: make([]KeyValue, 0, 1),
+		PerOperatorAmounts: make([]KeyValue, 0, len(amountPerOperator)),
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// new message to delegate asset to operator
func NewMsgDelegation(assetID, fromAddress string, amountPerOperator []KeyValue) *MsgDelegation {
baseInfo := &DelegationIncOrDecInfo{
FromAddress: fromAddress,
PerOperatorAmounts: make([]KeyValue, 0, 1),
}
for _, kv := range amountPerOperator {
baseInfo.PerOperatorAmounts = append(baseInfo.PerOperatorAmounts, KeyValue{Key: kv.Key, Value: kv.Value})
}
return &MsgDelegation{
AssetID: assetID,
BaseInfo: baseInfo,
// new message to delegate asset to operator
func NewMsgDelegation(assetID, fromAddress string, amountPerOperator []KeyValue) *MsgDelegation {
baseInfo := &DelegationIncOrDecInfo{
FromAddress: fromAddress,
PerOperatorAmounts: make([]KeyValue, 0, len(amountPerOperator)),
}
for _, kv := range amountPerOperator {
baseInfo.PerOperatorAmounts = append(baseInfo.PerOperatorAmounts, KeyValue{Key: kv.Key, Value: kv.Value})
}
return &MsgDelegation{
AssetID: assetID,
BaseInfo: baseInfo,

parsedStakerID := strings.Split(record.StakerID, "_")
stakerAddr := sdk.AccAddress(hexutil.MustDecode(parsedStakerID[0]))
if err := k.bankKeeper.UndelegateCoinsFromModuleToAccount(ctx, types.DelegatedPoolName, stakerAddr, sdk.NewCoins(sdk.NewCoin(assetstypes.NativeAssetDenom, record.ActualCompletedAmount))); err != nil {
panic(err)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Avoid panicking in EndBlock; handle errors gracefully

Using panic in the EndBlock method can cause the entire blockchain to halt if an error occurs. Instead, return the error to handle it gracefully and maintain chain stability.

Apply this diff to replace the panic with proper error handling:

-    panic(err)
+    return nil, err
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
panic(err)
return nil, err

Comment on lines +103 to +106
operatorAssetInfo, err := k.GetOperatorSpecifiedAssetInfo(ctx, sdk.MustAccAddressFromBech32(operator), assetID)
if err != nil {
return nil, errorsmod.Wrap(err, "failed to GetOperatorSpecifiedAssetInfo")
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Avoid potential panics by not using sdk.MustAccAddressFromBech32

Using sdk.MustAccAddressFromBech32 can lead to a panic if the operator address is invalid. To prevent this, use sdk.AccAddressFromBech32 and handle any errors gracefully.

Apply this diff to handle potential errors:

-operatorAssetInfo, err := k.GetOperatorSpecifiedAssetInfo(ctx, sdk.MustAccAddressFromBech32(operator), assetID)
+operatorAccAddr, err := sdk.AccAddressFromBech32(operator)
+if err != nil {
+    return nil, errorsmod.Wrapf(err, "invalid operator address: %s", operator)
+}
+operatorAssetInfo, err := k.GetOperatorSpecifiedAssetInfo(ctx, operatorAccAddr, assetID)
 if err != nil {
     return nil, errorsmod.Wrap(err, "failed to GetOperatorSpecifiedAssetInfo")
 }
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
operatorAssetInfo, err := k.GetOperatorSpecifiedAssetInfo(ctx, sdk.MustAccAddressFromBech32(operator), assetID)
if err != nil {
return nil, errorsmod.Wrap(err, "failed to GetOperatorSpecifiedAssetInfo")
}
operatorAccAddr, err := sdk.AccAddressFromBech32(operator)
if err != nil {
return nil, errorsmod.Wrapf(err, "invalid operator address: %s", operator)
}
operatorAssetInfo, err := k.GetOperatorSpecifiedAssetInfo(ctx, operatorAccAddr, assetID)
if err != nil {
return nil, errorsmod.Wrap(err, "failed to GetOperatorSpecifiedAssetInfo")
}

Comment on lines +145 to +187
// delegate exocore-native-token
delegationParams = &delegationtype.DelegationOrUndelegationParams{
ClientChainID: assetstypes.NativeChainLzID,
Action: types.DelegateTo,
AssetsAddress: common.HexToAddress(assetstypes.NativeAssetAddr).Bytes(),
OperatorAddress: opAccAddr,
StakerAddress: suite.accAddr[:],
OpAmount: sdkmath.NewInt(50),
LzNonce: 0,
TxHash: common.HexToHash("0x24c4a315d757249c12a7a1d7b6fb96261d49deee26f06a3e1787d008b445c3ac"),
}
err = suite.App.DelegationKeeper.DelegateTo(suite.Ctx, delegationParams)
suite.NoError(err)
// check delegation states
stakerID, assetID = types.GetStakeIDAndAssetID(delegationParams.ClientChainID, delegationParams.StakerAddress, delegationParams.AssetsAddress)
restakerState, err = suite.App.AssetsKeeper.GetStakerSpecifiedAssetInfo(suite.Ctx, stakerID, assetID)
suite.NoError(err)
balance := suite.App.BankKeeper.GetBalance(suite.Ctx, suite.accAddr, assetstypes.NativeAssetDenom)
suite.Equal(types.StakerAssetInfo{
TotalDepositAmount: balance.Amount.Add(delegationParams.OpAmount),
WithdrawableAmount: balance.Amount,
PendingUndelegationAmount: sdkmath.NewInt(0),
}, *restakerState)
operatorState, err = suite.App.AssetsKeeper.GetOperatorSpecifiedAssetInfo(suite.Ctx, opAccAddr, assetID)
suite.NoError(err)
suite.Equal(types.OperatorAssetInfo{
TotalAmount: delegationParams.OpAmount,
PendingUndelegationAmount: sdkmath.NewInt(0),
TotalShare: sdkmath.LegacyNewDecFromBigInt(delegationParams.OpAmount.BigInt()),
OperatorShare: sdkmath.LegacyNewDec(0),
}, *operatorState)

specifiedDelegationAmount, err = suite.App.DelegationKeeper.GetSingleDelegationInfo(suite.Ctx, stakerID, assetID, opAccAddr.String())
suite.NoError(err)
suite.Equal(delegationtype.DelegationAmounts{
UndelegatableShare: sdkmath.LegacyNewDecFromBigInt(delegationParams.OpAmount.BigInt()),
WaitUndelegationAmount: sdkmath.NewInt(0),
}, *specifiedDelegationAmount)

totalDelegationAmount, err = suite.App.DelegationKeeper.StakerDelegatedTotalAmount(suite.Ctx, stakerID, assetID)
suite.NoError(err)
suite.Equal(delegationParams.OpAmount, totalDelegationAmount)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Refactor to reduce duplication in TestDelegateTo

The added code for delegating native tokens closely mirrors the existing delegation test. Consider refactoring to eliminate duplication by parameterizing the asset details or utilizing helper functions to handle common logic.

Comment on lines +250 to +308

// undelegate exocore-native-token
delegationEvent = suite.prepareDelegationNativeToken()

err = suite.App.DelegationKeeper.UndelegateFrom(suite.Ctx, delegationEvent)
suite.NoError(err)

stakerID, assetID = types.GetStakeIDAndAssetID(delegationEvent.ClientChainID, delegationEvent.StakerAddress, delegationEvent.AssetsAddress)
restakerState, err = suite.App.AssetsKeeper.GetStakerSpecifiedAssetInfo(suite.Ctx, stakerID, assetID)
suite.NoError(err)
balance := suite.App.BankKeeper.GetBalance(suite.Ctx, suite.accAddr, assetstypes.NativeAssetDenom)
suite.Equal(types.StakerAssetInfo{
TotalDepositAmount: balance.Amount.Add(delegationEvent.OpAmount),
WithdrawableAmount: balance.Amount,
PendingUndelegationAmount: delegationEvent.OpAmount,
}, *restakerState)

operatorState, err = suite.App.AssetsKeeper.GetOperatorSpecifiedAssetInfo(suite.Ctx, delegationEvent.OperatorAddress, assetID)
suite.NoError(err)
suite.Equal(types.OperatorAssetInfo{
TotalAmount: sdkmath.NewInt(0),
PendingUndelegationAmount: delegationEvent.OpAmount,
TotalShare: sdkmath.LegacyNewDec(0),
OperatorShare: sdkmath.LegacyNewDec(0),
}, *operatorState)

specifiedDelegationAmount, err = suite.App.DelegationKeeper.GetSingleDelegationInfo(suite.Ctx, stakerID, assetID, delegationEvent.OperatorAddress.String())
suite.NoError(err)
suite.Equal(delegationtype.DelegationAmounts{
WaitUndelegationAmount: delegationEvent.OpAmount,
UndelegatableShare: sdkmath.LegacyNewDec(0),
}, *specifiedDelegationAmount)

totalDelegationAmount, err = suite.App.DelegationKeeper.StakerDelegatedTotalAmount(suite.Ctx, stakerID, assetID)
suite.NoError(err)
suite.Equal(sdkmath.NewInt(0), totalDelegationAmount)

records, err = suite.App.DelegationKeeper.GetStakerUndelegationRecords(suite.Ctx, stakerID, assetID)
suite.NoError(err)
suite.Equal(1, len(records))
UndelegationRecord = &delegationtype.UndelegationRecord{
StakerID: stakerID,
AssetID: assetID,
OperatorAddr: delegationEvent.OperatorAddress.String(),
TxHash: delegationEvent.TxHash.String(),
IsPending: true,
BlockNumber: uint64(suite.Ctx.BlockHeight()),
LzTxNonce: delegationEvent.LzNonce,
Amount: delegationEvent.OpAmount,
ActualCompletedAmount: delegationEvent.OpAmount,
}
UndelegationRecord.CompleteBlockNumber = UndelegationRecord.BlockNumber + delegationtype.CanUndelegationDelayHeight
suite.Equal(UndelegationRecord, records[0])

suite.Ctx.Logger().Info("the complete block number is:", "height", UndelegationRecord.CompleteBlockNumber)
waitUndelegationRecords, err = suite.App.DelegationKeeper.GetPendingUndelegationRecords(suite.Ctx, UndelegationRecord.CompleteBlockNumber)
suite.NoError(err)
suite.Equal(2, len(waitUndelegationRecords))
suite.Equal(UndelegationRecord, waitUndelegationRecords[0])
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Eliminate repetitive code in TestUndelegateFrom

The new code segment for undelegating native tokens replicates existing logic. To enhance maintainability, refactor the test to use shared helper methods for common operations.

Comment on lines +70 to +84
func (suite *DelegationTestSuite) prepareDelegationNativeToken() *delegationtype.DelegationOrUndelegationParams {
delegationEvent := &delegationtype.DelegationOrUndelegationParams{
ClientChainID: assetstypes.NativeChainLzID,
Action: types.DelegateTo,
AssetsAddress: common.HexToAddress(assetstypes.NativeAssetAddr).Bytes(),
OperatorAddress: suite.opAccAddr,
StakerAddress: suite.accAddr[:],
OpAmount: suite.delegationAmount,
LzNonce: 0,
TxHash: common.HexToHash("0x24c4a315d757249c12a7a1d7b6fb96261d49deee26f06a3e1787d008b445c3ac"),
}
err := suite.App.DelegationKeeper.DelegateTo(suite.Ctx, delegationEvent)
suite.NoError(err)
return delegationEvent
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Include operator registration in prepareDelegationNativeToken

The method prepareDelegationNativeToken lacks the operator registration step present in prepareDelegation. To prevent potential errors during delegation, ensure that the operator is registered before delegating native tokens.

Apply this diff to include operator registration:

 func (suite *DelegationTestSuite) prepareDelegationNativeToken() *delegationtype.DelegationOrUndelegationParams {
+	registerReq := &operatortype.RegisterOperatorReq{
+		FromAddress: suite.opAccAddr.String(),
+		Info: &operatortype.OperatorInfo{
+			EarningsAddr: suite.opAccAddr.String(),
+		},
+	}
+	_, err := s.OperatorMsgServer.RegisterOperator(s.Ctx, registerReq)
+	suite.NoError(err)

 	delegationEvent := &delegationtype.DelegationOrUndelegationParams{
 		// existing code...
 	}
 	err := suite.App.DelegationKeeper.DelegateTo(suite.Ctx, delegationEvent)
 	suite.NoError(err)
 	return delegationEvent
 }

Committable suggestion was skipped due to low confidence.

Comment on lines +737 to +745
- ERC-20 Middleware
- Recovery Middleware
- IBC Transfer

SendPacket, since it is originating from the application to core IBC:
transferKeeper.SendPacket -> recovery.SendPacket -> erc20.SendPacket -> channel.SendPacket
transferKeeper.SendPacket -> recovery.SendPacket -> erc20.SendPacket -> channel.SendPacket

RecvPacket, message that originates from core IBC and goes down to app, the flow is the other way
channel.RecvPacket -> erc20.OnRecvPacket -> recovery.OnRecvPacket -> transfer.OnRecvPacket
channel.RecvPacket -> erc20.OnRecvPacket -> recovery.OnRecvPacket -> transfer.OnRecvPacket
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Update comments to reflect current transfer stack

The comments mention Recovery Middleware, but it appears the recovery middleware is no longer part of the transfer stack. Please update the comments to accurately represent the current middleware configuration.

Apply this diff to correct the comments:

-	// transfer stack contains (from bottom to top):
-	// - ERC-20 Middleware
-	// - Recovery Middleware
-	// - IBC Transfer
+	// Transfer stack contains (from bottom to top):
+	// - ERC-20 Middleware
+	// - IBC Transfer

-	transferKeeper.SendPacket -> recovery.SendPacket -> erc20.SendPacket -> channel.SendPacket
+	transferKeeper.SendPacket -> erc20.SendPacket -> channel.SendPacket

-	channel.RecvPacket -> erc20.OnRecvPacket -> recovery.OnRecvPacket -> transfer.OnRecvPacket
+	channel.RecvPacket -> erc20.OnRecvPacket -> transfer.OnRecvPacket
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
- ERC-20 Middleware
- Recovery Middleware
- IBC Transfer
SendPacket, since it is originating from the application to core IBC:
transferKeeper.SendPacket -> recovery.SendPacket -> erc20.SendPacket -> channel.SendPacket
transferKeeper.SendPacket -> recovery.SendPacket -> erc20.SendPacket -> channel.SendPacket
RecvPacket, message that originates from core IBC and goes down to app, the flow is the other way
channel.RecvPacket -> erc20.OnRecvPacket -> recovery.OnRecvPacket -> transfer.OnRecvPacket
channel.RecvPacket -> erc20.OnRecvPacket -> recovery.OnRecvPacket -> transfer.OnRecvPacket
// Transfer stack contains (from bottom to top):
// - ERC-20 Middleware
// - IBC Transfer
SendPacket, since it is originating from the application to core IBC:
transferKeeper.SendPacket -> erc20.SendPacket -> channel.SendPacket
RecvPacket, message that originates from core IBC and goes down to app, the flow is the other way
channel.RecvPacket -> erc20.OnRecvPacket -> transfer.OnRecvPacket

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
C:CLI C:Proto enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants